我使用 postgres 从 postgres 数据库获取数据。因此,创建flask api,但是当我使用curl命令时,它会返回400 bad request错误。 这是我的代码 -
from flask import Flask, render_template, request, Response
import psycopg2
import csv
import json
from psycopg2.extras import RealDictCursor
import requests
conn = psycopg2.connect("host='localhost' dbname='postgres' user='postgres'")
app = Flask(__name__)
@app.route('/', methods = ['GET','POST'])
def index():
cur = conn.cursor(cursor_factory=RealDictCursor)
query = request.form['query']
cur.execute(query)
return Response(json.dumps(cur.fetchall(),indent=2),mimetype='application/json')
if __name__ == "__main__":
app.run(host='0.0.0.0')
conn.close()
我使用这个curl命令-
curl -H "Content-Type: application/json" -X GET http://127.0.0.1:5000/ -d '{"query":"SELECT COUNT(*) FROM usage"}'
那么如何将curl与flask api一起使用。
您可以直接进行 SQL 注入。我建议你修复一下。
请求不是这样工作的。如果您想在
curl
中传递数据,则参数的格式需要像查询字符串一样。它不会为您解码 JSON。您有几个选择。
(注意,我对每个参数进行了编码)
重新格式化curl以使用GET参数:
curl 'http://127.0.0.1:5000/?query=SELECT%20COUNT(*)%20FROM%20usage'
按预期将curl重新格式化为POST:
curl -H "Content-Type: application/json" -X POST http://127.0.0.1:5000/ -d 'query=SELECT%20COUNT(*)%20FROM%20usage'
这将使您获得上面编写的数据。
这将让您继续使用您编写的 cURL:
# this is the short version, provided by randomir in the comments.
query = request.json().get('query')
# This is an alternative which roughly does the same thing
dat_str = request.data
dat_dict = json.loads(dat_str)
query = dat_dict['query']
对于像我一样后来发现这一点的人。在尝试测试我的 webhook 接收器时,我使用类似的 get 请求遇到了相同的错误。我通过更改卷曲请求解决了这个问题:
curl -H "Content-Type: application/json" -X POST http://xxx.x.x.x:5000/ -d '{"key": "value"}'
到
curl -H "Content-Type: application/json" -X POST http://xxx.x.x.x:5000/ -d "{\"key\": \"value\"}"