cURL 命令返回 400 Bad request 错误

问题描述 投票:0回答:2

我使用 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一起使用。

python postgresql curl flask flask-sqlalchemy
2个回答
1
投票

免责声明:

您可以直接进行 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'

这将使您获得上面编写的数据。

解析 JSON

这将让您继续使用您编写的 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']

0
投票

对于像我一样后来发现这一点的人。在尝试测试我的 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\"}"
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.