在Flas中访问传入的POST数据

2024-10-01 09:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是烧瓶代码:

from flask import Flask, request
import json
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def refresh():
    params = {
        'thing1': request.values.get('thing1'),
        'thing2': request.values.get('thing2')
    }
    return json.dumps(params)

这是cURL

$ curl -XGET 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'                                              
> {"thing1": "1", "thing2": null}

$ curl -XGET 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'                                              
> {"thing1": "1", "thing2": null}

docs似乎非常清楚,这应该是可行的:

form

A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.

args

A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

values

A CombinedMultiDict with the contents of both form and args.

你知道我做错了什么吗?

更新:尝试其中一个答案的建议,换掉return行:

使用return json.dumps(json.load(request.body.decode("utf-8") ))生成错误AttributeError: 'Request' object has no attribute 'body'

使用return json.dumps(json.load(request.json))生成错误AttributeError: 'NoneType' object has no attribute 'read'

对源代码使用POST似乎没有效果:

$ curl -XPOST 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
{"thing1": "1", "thing2": null}

设置内容类型并对原始代码使用POST也没有明显效果:

$ curl -XPOST -H "Content-Type: application/json" 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}' 
{"thing1": "1", "thing2": null}

尽管我去验证了内容类型的设置是否正确:

...
print(request.headers)
...

Host: 127.0.0.1:5000
User-Agent: curl/7.54.0
Accept: */*
Content-Type: application/json
Content-Length: 12

Tags: theinformjsonhttpreturnrequestwith
1条回答
网友
1楼 · 发布于 2024-10-01 09:42:11

您无意中发送了错误的Content Type

默认情况下,^{}'s ^{} flag will send POST data with content-type ^{}。因为您没有按预期格式发送数据(key=value),所以它会完全删除数据。对于JSON数据,您需要发送内容类型设置为application/json的HTTP请求,如下所示:

curl -XPOST -H "Content-Type: application/json" 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'

另外,flask的request.form字段只包含POST form data,而不包含其他内容类型。您可以使用^{}或更方便地使用^{}解析的JSON数据访问原始POST请求体。

下面是示例的固定版本:

from flask import Flask, request
import json
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def refresh():
    params = {
        'thing1': request.values.get('thing1'),
        'thing2': request.get_json().get('thing2')
    }
    return json.dumps(params)


app.run()

更新:我之前说错了-request.body实际上应该是request.data。同样,现在应该使用^{} is deprecatedrequest.get_json。原帖已更新。

相关问题 更多 >