获取 Flask 请求中收到的数据
我希望能够将数据发送到我的 Flask 应用程序。我尝试访问 request.data
但它是一个空字符串。如何访问请求数据?
from flask import request
@app.route('/', methods=['GET', 'POST'])
def parse_request():
data = request.data # data is empty
# need posted data here
这个问题的答案让我问在Python Flask中获取原始POST正文,无论Content-Type标头如何,这是关于获取原始数据而不是解析后的数据。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
在编写应该发送 JSON 数据的 Slack 机器人时,我得到了一个有效负载,其中
Content-Type
为application/x-www-form-urlencoded
。我尝试了
request.get_json()
但没有成功。相反,我使用 request.form 来获取包含 JSON 的表单数据字段,然后加载它。
When writing a Slack bot, which is supposed to send JSON data, I got a payload where the
Content-Type
wasapplication/x-www-form-urlencoded
.I tried
request.get_json()
and it didn't work.Instead I used
request.form
to get the form data field that contained JSON, then loaded that.如果内容类型被识别为表单数据,
request.data
会将其解析为request.form
并返回一个空字符串。要获取原始数据(无论内容类型如何),请调用
request.get_data()< /代码>
。
request.data
调用get_data(parse_form_data=True)
,如果直接调用,默认值为False
。If the content type is recognized as form data,
request.data
will parse that intorequest.form
and return an empty string.To get the raw data regardless of content type, call
request.get_data()
.request.data
callsget_data(parse_form_data=True)
, while the default isFalse
if you call it directly.使用 HTML 表单发布表单数据时,请确保
input
标记具有name
属性,否则它们不会出现在request.form
中。只有
txt3
输入具有name
,因此它是request.form
中存在的唯一键。When posting form data with an HTML form, be sure the
input
tags havename
attributes, otherwise they won't be present inrequest.form
.Only the
txt3
input had aname
, so it's the only key present inrequest.form
.要获取表单数据,请尝试此操作,请求对象允许我们访问来自请求的数据。它还可以帮助我们访问有关请求的其他信息。希望有帮助。 :)
To get form data, try this, The request object allows us to get access to the data that come from a request. it can also help us access other information about a request. Hope that helps. :)
试试这个
它将把表单和 JSON 数据放在一起并将其转换成字典
Try this
It'll get both the form and JSON data together and convert it into the dictionary
我浏览了上面的所有答案,但是,我注意到没有人真正谈论当您从客户端(当您的客户端具有不同来源,例如反应应用程序)接收数据到服务器端时,那么您还需要处理
OPTIONS
飞行前请求允许跨源访问,否则会引发 CORS 错误。处理完之后,通常的过程是在request
对象上使用get_json()
方法。以下是适合我的代码:还要确保将
request.get_json()
放在 elif 块中,而不是放在函数的开头。否则,您将在客户端遇到 CORS 错误,并可能在服务器端遇到 415 错误,因为当您收到飞行前 OPTIONS 请求时,该函数将尝试将其解码为 json,因为您放置了request.get_json()< /code> 开头,因此,以下控制流程是错误的:
I went through all the answers above, however, I noticed no one really talked about when you receive data from Client-side (when your client side is of different origin e.g. react app) to Server-side then you also need to handle
OPTIONS
pre-flight request in Flask to allow Cross-Origin access otherwise CORS error is thrown. After you handle that, then usual process is to useget_json()
method onrequest
object. Following is the code that works for me:Also make sure you put
request.get_json()
in elif block not at the beginning of function. Otherwise you will encounter the CORS error at client-side and possibly 415 error at server side because when you receive the pre-flight OPTIONS request the function will try to decode it as json because you placed therequest.get_json()
at the beginning, therefore, following control-flow is wrong:我刚刚面临同样的需求。我必须保存信息以防出现意外情况。因此,我使用以下公式:
repr(request) 将给出基本信息的字符串表示形式。您可以使用以下方式添加用户代理数据:
request.headers.get('User-Agent')
我还保存了会话大陆,因为它可能包含有价值的信息
I just faced the same need. I have to save information in case of any unexpected situation. So, I use the following formula:
repr(request) will give a string representation of the basic information. You could add user-agent data with:
request.headers.get('User-Agent')
I also save the session continent as it could contain valuable information
这很好用,但请记住它作为字符串输入,并且需要迭代。
This is great to use but remember that it comes in as a string and will need iterated through.
尝试->
Try - >
docs 描述了
request
对象上可用的属性 (fromflask import request
)在请求期间。在大多数常见情况下,request.data
将为空,因为它用作后备:request.args
:键/值对在 URL 查询字符串request.form
中:正文中的键/值对,来自 HTML 发布表单,或非 JSON 编码的 JavaScript 请求请求。 files
:主体中的文件,Flask 将其与form
分开。 HTML 表单必须使用enctype=multipart/form-data
否则文件将无法上传。request.values
:组合args args
form
,如果键重叠 rel="noreferrer">request.json
:解析的 JSON 数据。请求必须具有application/json
内容类型,或使用request.get_json(force=True)
忽略内容类型。所有这些都是
MultiDict
实例(除了json
)。您可以使用以下方式访问值:request.form['name']
:如果您知道键存在,则使用索引request.form.get('name')
:使用 < code>get 如果密钥可能不存在request.form.getlist('name')
:如果多次发送密钥并且您想要使用getlist
值列表。get
仅返回第一个值。The docs describe the attributes available on the
request
object (from flask import request
) during a request. In most common casesrequest.data
will be empty because it's used as a fallback:request.args
: the key/value pairs in the URL query stringrequest.form
: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files
: the files in the body, which Flask keeps separate fromform
. HTML forms must useenctype=multipart/form-data
or files will not be uploaded.request.values
: combinedargs
andform
, preferringargs
if keys overlaprequest.json
: parsed JSON data. The request must have theapplication/json
content type, or userequest.get_json(force=True)
to ignore the content type.All of these are
MultiDict
instances (except forjson
). You can access values using:request.form['name']
: use indexing if you know the key existsrequest.form.get('name')
: useget
if the key might not existrequest.form.getlist('name')
: usegetlist
if the key is sent multiple times and you want a list of values.get
only returns the first value.对于 URL 查询参数,请使用
request.args
。对于发布的表单输入,请使用
request.form
。对于使用内容类型
application/json
发布的 JSON,请使用request.get_json()
。For URL query parameters, use
request.args
.For posted form input, use
request.form
.For JSON posted with content type
application/json
, userequest.get_json()
.要获取原始数据,请使用
request.data
。仅当无法将其解析为表单数据时,此方法才有效,否则它将为空,并且request.form
将包含已解析的数据。To get the raw data, use
request.data
. This only works if it couldn't be parsed as form data, otherwise it will be empty andrequest.form
will have the parsed data.下面是解析发布的 JSON 数据并回显它的示例。
要使用curl发布JSON:
或者使用Postman:
Here's an example of parsing posted JSON data and echoing it back.
To post JSON with curl:
Or to use Postman:
要获取原始帖子正文(无论内容类型如何),请使用
request.get_data()
。如果您使用request.data
,它会调用request.get_data(parse_form_data=True)
,这将填充request.form
MultiDict
并将data
留空。To get the raw post body regardless of the content type, use
request.get_data()
. If you userequest.data
, it callsrequest.get_data(parse_form_data=True)
, which will populate therequest.form
MultiDict
and leavedata
empty.如果您发布内容类型为
application/json
的 JSON,请使用request.get_json()
在 Flask 中获取它。如果内容类型不正确,则返回None
。如果数据不是 JSON,则会引发错误。If you post JSON with content type
application/json
, userequest.get_json()
to get it in Flask. If the content type is not correct,None
is returned. If the data is not JSON, an error is raised.要将
request.form
作为普通字典获取,请使用request.form.to_dict(flat=False)
。要返回 API 的 JSON 数据,请将其传递给
jsonify
。此示例将表单数据作为 JSON 数据返回。
以下是使用curl 的POST 表单数据示例,以JSON 形式返回:
To get
request.form
as a normal dictionary , userequest.form.to_dict(flat=False)
.To return JSON data for an API, pass it to
jsonify
.This example returns form data as JSON data.
Here's an example of POST form data with curl, returning as JSON:
对于表单数据,您可以从
request.form
获取请求数据request.json
和request.get_json
获取请求数据datarequest.headers
用于标头request.args
获取查询参数它们都像字典,使用
request.form['name']
如果您知道密钥存在,或者request.form.get('name')
如果它是可选的。You can get request data from
request.form
for form data, this includes form and file data,request.json
andrequest.get_json
for JSON datarequest.headers
for headersrequest.args
to get query paramsThey're all like a dictionary, use
request.form['name']
if you know the key exists, orrequest.form.get('name')
if it is optional.使用
request.get_json()
获取发布的 JSON 数据。使用 POST 方法提交表单时,使用
request.form
获取数据。使用
request.args
获取 URL 查询字符串中传递的数据,就像使用 GET 方法提交表单时一样。request.form
等类似于字典,如果未传递,则使用get
方法获取默认值。Use
request.get_json()
to get posted JSON data.Use
request.form
to get data when submitting a form with the POST method.Use
request.args
to get data passed in the query string of the URL, like when submitting a form with the GET method.request.form
etc. are dict-like, use theget
method to get a value with a default if it wasn't passed.导入请求:
URL 查询参数:
表单输入:
OR(如果您知道密钥存在,则使用索引,指定输入字段的名称)
JSON 数据(对于内容类型 application/json >)
Import request:
URL query parameters:
Form Input:
OR (use indexing if you know the key exists, specify the name of input fields)
JSON Data (for content type application/json)
要在不使用
application/json
内容类型的情况下发布 JSON,请使用request.get_json(force=True)
。To get JSON posted without the
application/json
content type, userequest.get_json(force=True)
.要在 JavaScript 中使用 jQuery 发布 JSON,请使用 JSON.stringify 转储数据,并将内容类型设置为 application/json。
在 Flask 中使用
request.get_json()
解析它。To post JSON with jQuery in JavaScript, use
JSON.stringify
to dump the data, and set the content type toapplication/json
.Parse it in Flask with
request.get_json()
.原始数据作为
request.stream
从 WSGI 服务器传递到 Flask 应用程序。流的长度位于Content-Length
标头中。通常使用
request.get_data()
更安全。The raw data is passed in to the Flask application from the WSGI server as
request.stream
. The length of the stream is in theContent-Length
header.It is usually safer to use
request.get_data()
instead.以下是发布表单数据以将用户添加到数据库的示例。检查
request.method == "POST"
以检查表单是否已提交。使用request.form
中的键获取表单数据。否则使用Here's an example of posting form data to add a user to a database. Check
request.method == "POST"
to check if the form was submitted. Use keys fromrequest.form
to get the form data. Render an HTML template with a<form>
otherwise. The fields in the form should havename
attributes that match the keys inrequest.form
.要解析 JSON,请使用
request.get_json()
。To parse JSON, use
request.get_json()
.如果正文被识别为表单数据,它将位于
request.form
中。如果是 JSON,则位于request.get_json()
中。否则原始数据将位于request.data
中。如果您不确定如何提交数据,可以使用or
链来获取第一个包含数据的链。request.args
包含从查询字符串解析的参数,无论主体中包含什么,因此如果它和主体都应该数据,则可以从get_request_data()
中删除它同时。If the body is recognized as form data, it will be in
request.form
. If it's JSON, it will be inrequest.get_json()
. Otherwise the raw data will be inrequest.data
. If you're not sure how data will be submitted, you can use anor
chain to get the first one with data.request.args
contains args parsed from the query string, regardless of what was in the body, so you would remove that fromget_request_data()
if both it and a body should data at the same time.