在Flask中访问传入的POST数据 [英] Accessing incoming POST data in Flask

查看:176
本文介绍了在Flask中访问传入的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.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}

文档似乎非常清楚,这应该可行:

The docs seem VERY clear that this should be working:


form

form

MultiDict具有从POST或PUT请求中解析出的表单数据。
请记住,文件上传不会在这里结束,而是
会在files属性中结束。

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

具有查询字符串的已解析内容的MultiDict。 (问号后URL中的
部分)。

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

A CombinedMultiDict with

A CombinedMultiDict with the contents of both form and args.

有什么想法我做错了吗?

Any ideas what I'm doing wrong?

更新:尝试从答案之一中获取建议,换出返回行:

Update: Trying suggestions from one of the answers, swapping out the return line:

使用返回json.dumps(json.load(request.body.decode( utf-8)))生成错误 AttributeError:'Request'对象没有属性'body'

使用返回json.dumps(json.load(request.json)) 生成错误 AttributeError:'NoneType'对象没有属性'read'

POST 与原始代码一起使用似乎无效:

Using POST with the origin code appears to have no effect:

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

设置内容类型并使用 POST 与原始代码也没有明显的作用:

Setting the content type and using POST with the original code also has no apparent effect:

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

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

although I went and verified that the content-type was then correctly set:

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

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


推荐答案

您无意中发送了错误的内容类型

You're inadvertently sending the wrong Content Type.

默认情况下, curl -d 标志将发送内容类型为 application / x-www-for的POST数据m-urlencoded 。由于您未按照预期的格式( key = value )发送数据,因此将数据全部删除。对于JSON数据,您需要发送内容类型设置为 application / json 的HTTP请求,如下所示:

By default, curl's -d flag will send POST data with content-type application/x-www-form-urlencoded. Since you're not sending data in the format that it's expecting (key=value), it's dropping the data altogether. For JSON data, you'll need to send the HTTP request with the content-type set to application/json like so:

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

而且,烧瓶的 request.form 字段仅包含 POST表单数据,而不包含其他内容类型。您可以使用 request访问原始POST请求正文.data ,或更方便的是,使用 request.get_json

Also, flask's request.form field only contains POST form data, not other content types. You can access the raw POST request body with request.data or, more convenienty, the parsed JSON data using request.get_json.

以下是您的固定版本例如:

Below is a fixed version of your example:

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 。事实证明, request.json 已弃用,现在应改为使用 request.get_json 。原始帖子已更新。

UPDATE: I misspoke earlier - request.body should actually be request.data. Also as it turns out request.json is deprecated and request.get_json should be used now instead. The original post has been updated.

这篇关于在Flask中访问传入的POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆