获取 Flask 请求中收到的数据

发布于 2025-01-12 11:27:51 字数 444 浏览 0 评论 0 原文

我希望能够将数据发送到我的 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标头如何,这是关于获取原始数据而不是解析后的数据。

I want to be able to get the data sent to my Flask app. I've tried accessing request.data but it is an empty string. How do you access request data?

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data = request.data  # data is empty
    # need posted data here

The answer to this question led me to ask Get raw POST body in Python Flask regardless of Content-Type header next, which is about getting the raw data rather than the parsed data.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

江挽川 2025-01-19 11:27:52

在编写应该发送 JSON 数据的 Slack 机器人时,我得到了一个有效负载,其中 Content-Typeapplication/x-www-form-urlencoded

我尝试了 request.get_json() 但没有成功。

@app.route('/process_data', methods=['POST'])
def process_data():
   req_data = request.get_json(force=True)

相反,我使用 request.form 来获取包含 JSON 的表单数据字段,然后加载它。

from flask import json

@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
   req_data = json.loads(request.form["payload"])

When writing a Slack bot, which is supposed to send JSON data, I got a payload where the Content-Type was application/x-www-form-urlencoded.

I tried request.get_json() and it didn't work.

@app.route('/process_data', methods=['POST'])
def process_data():
   req_data = request.get_json(force=True)

Instead I used request.form to get the form data field that contained JSON, then loaded that.

from flask import json

@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
   req_data = json.loads(request.form["payload"])
淡看悲欢离合 2025-01-19 11:27:52

如果内容类型被识别为表单数据,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 into request.form and return an empty string.

To get the raw data regardless of content type, call request.get_data(). request.data calls get_data(parse_form_data=True), while the default is False if you call it directly.

还不是爱你 2025-01-19 11:27:52
@app.route('/addData', methods=['POST'])
def add_data():
     data_in = mongo.db.Data
     id = request.values.get("id")
     name = request.values.get("name")
     newuser = {'id' : id, 'name' : name}
     if voter.find({'id' : id, 'name' : name}).count() > 0:
            return "Data Exists"
     else:
            data_in.insert(newuser)
            return "Data Added"
@app.route('/addData', methods=['POST'])
def add_data():
     data_in = mongo.db.Data
     id = request.values.get("id")
     name = request.values.get("name")
     newuser = {'id' : id, 'name' : name}
     if voter.find({'id' : id, 'name' : name}).count() > 0:
            return "Data Exists"
     else:
            data_in.insert(newuser)
            return "Data Added"
遮了一弯 2025-01-19 11:27:52

使用 HTML 表单发布表单数据时,请确保 input 标记具有 name 属性,否则它们不会出现在 request.form 中。

@app.route('/', methods=['GET', 'POST'])
def index():
    print(request.form)
    return """
<form method="post">
    <input type="text">
    <input type="text" id="txt2">
    <input type="text" name="txt3" id="txt3">  
    <input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])

只有 txt3 输入具有 name,因此它是 request.form 中存在的唯一键。

When posting form data with an HTML form, be sure the input tags have name attributes, otherwise they won't be present in request.form.

@app.route('/', methods=['GET', 'POST'])
def index():
    print(request.form)
    return """
<form method="post">
    <input type="text">
    <input type="text" id="txt2">
    <input type="text" name="txt3" id="txt3">  
    <input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])

Only the txt3 input had a name, so it's the only key present in request.form.

征﹌骨岁月お 2025-01-19 11:27:52

要获取表单数据,请尝试此操作,请求对象允许我们访问来自请求的数据。它还可以帮助我们访问有关请求的其他信息。希望有帮助。 :)

from flask import Flask, request


app = Flask(__name__)

@app.get('/')
def index():
  json_data = request.get_json() #this will get the json data and return a dictionary containing the data sent
  
  form_data = request.form #this will get the form data return a dictionary of the data submitted in a form


  #such can be accessed in the following way
   username = json_data.get('username')
   email = form_data.get('email') # this will be value from the email input
  ....

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. :)

from flask import Flask, request


app = Flask(__name__)

@app.get('/')
def index():
  json_data = request.get_json() #this will get the json data and return a dictionary containing the data sent
  
  form_data = request.form #this will get the form data return a dictionary of the data submitted in a form


  #such can be accessed in the following way
   username = json_data.get('username')
   email = form_data.get('email') # this will be value from the email input
  ....
只想待在家 2025-01-19 11:27:52

试试这个

 json_data = request.form or request.get_json()
 data = dict(json_data)

它将把表单和 JSON 数据放在一起并将其转换成字典

Try this

 json_data = request.form or request.get_json()
 data = dict(json_data)

It'll get both the form and JSON data together and convert it into the dictionary

歌枕肩 2025-01-19 11:27:52

我浏览了上面的所有答案,但是,我注意到没有人真正谈论当您从客户端(当您的客户端具有不同来源,例如反应应用程序)接收数据到服务器端时,那么您还需要处理 OPTIONS 飞行前请求允许跨源访问,否则会引发 CORS 错误。处理完之后,通常的过程是在 request 对象上使用 get_json() 方法。以下是适合我的代码:

@app.route("/read_row_to_customer_sheet", methods=["POST", "OPTIONS"])
def read_row_to_customer_sheet():
    if request.method == "OPTIONS":
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "*")
        response.headers.add("Content-Type", "application/json")
        return response
    elif request.method == 'POST':
        form = request.get_json()
        print(form)
        # your custom logic goes here
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response 

还要确保将 request.get_json() 放在 elif 块中,而不是放在函数的开头。否则,您将在客户端遇到 CORS 错误,并可能在服务器端遇到 415 错误,因为当您收到飞行前 OPTIONS 请求时,该函数将尝试将其解码为 json,因为您放置了 request.get_json()< /code> 开头,因此,以下控制流程是错误的:

### WRONG Route Function
@app.route("/read_row_to_customer_sheet", methods=["POST", "OPTIONS"])
def read_row_to_customer_sheet():
    form = request.get_json()
    if request.method == "OPTIONS":
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "*")
        response.headers.add("Content-Type", "application/json")
        return response
    elif request.method == 'POST':
        print(form)
        # your custom logic goes here
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response 

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 use get_json() method on request object. Following is the code that works for me:

@app.route("/read_row_to_customer_sheet", methods=["POST", "OPTIONS"])
def read_row_to_customer_sheet():
    if request.method == "OPTIONS":
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "*")
        response.headers.add("Content-Type", "application/json")
        return response
    elif request.method == 'POST':
        form = request.get_json()
        print(form)
        # your custom logic goes here
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response 

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 the request.get_json() at the beginning, therefore, following control-flow is wrong:

### WRONG Route Function
@app.route("/read_row_to_customer_sheet", methods=["POST", "OPTIONS"])
def read_row_to_customer_sheet():
    form = request.get_json()
    if request.method == "OPTIONS":
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "*")
        response.headers.add("Content-Type", "application/json")
        return response
    elif request.method == 'POST':
        print(form)
        # your custom logic goes here
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response 
清晨说晚安 2025-01-19 11:27:52

我刚刚面临同样的需求。我必须保存信息以防出现意外情况。因此,我使用以下公式:

Info = "%s/%s/%s" % (request.remote_addr, repr(request), repr(session))

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:

Info = "%s/%s/%s" % (request.remote_addr, repr(request), repr(session))

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

断舍离 2025-01-19 11:27:52
request.data

这很好用,但请记住它作为字符串输入,并且需要迭代。

request.data

This is great to use but remember that it comes in as a string and will need iterated through.

风为裳 2025-01-19 11:27:52

尝试->

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    if request.method == 'POST':
       data = request.form.get('data')

Try - >

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    if request.method == 'POST':
       data = request.form.get('data')
琉璃梦幻 2025-01-19 11:27:51

docs 描述了 request 对象上可用的属性 ( fromflask import request)在请求期间。在大多数常见情况下,request.data 将为空,因为它用作后备:

request.data 包含传入的请求数据作为字符串,以防它带有 Flask 无法处理的 mimetype。

所有这些都是 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 cases request.data will be empty because it's used as a fallback:

request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

  • request.args: the key/value pairs in the URL query string
  • request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded
  • request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.
  • request.values: combined args and form, preferring args if keys overlap
  • request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

All of these are MultiDict instances (except for json). You can access values using:

  • request.form['name']: use indexing if you know the key exists
  • request.form.get('name'): use get if the key might not exist
  • request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value.
万劫不复 2025-01-19 11:27:51

对于 URL 查询参数,请使用 request.args

search = request.args.get("search")
page = request.args.get("page")

对于发布的表单输入,请使用 request.form

email = request.form.get('email')
password = request.form.get('password')

对于使用内容类型 application/json 发布的 JSON,请使用 request.get_json()

data = request.get_json()

For URL query parameters, use request.args.

search = request.args.get("search")
page = request.args.get("page")

For posted form input, use request.form.

email = request.form.get('email')
password = request.form.get('password')

For JSON posted with content type application/json, use request.get_json().

data = request.get_json()
年华零落成诗 2025-01-19 11:27:51

要获取原始数据,请使用 request.data。仅当无法将其解析为表单数据时,此方法才有效,否则它将为空,并且 request.form 将包含已解析的数据。

from flask import request
request.data

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 and request.form will have the parsed data.

from flask import request
request.data
━╋う一瞬間旳綻放 2025-01-19 11:27:51

下面是解析发布的 JSON 数据并回显它的示例。

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

要使用curl发布JSON:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

或者使用Postman:

使用邮递员发布 JSON

Here's an example of parsing posted JSON data and echoing it back.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

To post JSON with curl:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

Or to use Postman:

using postman to post JSON

撩动你心 2025-01-19 11:27:51

要获取原始帖子正文(无论内容类型如何),请使用 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 use request.data, it calls request.get_data(parse_form_data=True), which will populate the request.form MultiDict and leave data empty.

亚希 2025-01-19 11:27:51

如果您发布内容类型为 application/json 的 JSON,请使用 request.get_json() 在 Flask 中获取它。如果内容类型不正确,则返回 None。如果数据不是 JSON,则会引发错误。

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()

If you post JSON with content type application/json, use request.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.

@app.route("/something", methods=["POST"])
def do_something():
    data = request.get_json()
囍笑 2025-01-19 11:27:51

要将 request.form 作为普通字典获取,请使用 request.form.to_dict(flat=False)

要返回 API 的 JSON 数据,请将其传递给 jsonify

此示例将表单数据作为 JSON 数据返回。

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

以下是使用curl 的POST 表单数据示例,以JSON 形式返回:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

To get request.form as a normal dictionary , use request.form.to_dict(flat=False).

To return JSON data for an API, pass it to jsonify.

This example returns form data as JSON data.

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

Here's an example of POST form data with curl, returning as JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}
夏雨凉 2025-01-19 11:27:51

对于表单数据,您可以从 request.form 获取请求数据

  1. ,这包括表单和文件数据,
  2. 对于 JSON,您可以从 request.jsonrequest.get_json 获取请求数据data
  3. request.headers 用于标头
  4. request.args 获取查询参数

它们都像字典,使用 request.form['name'] 如果您知道密钥存在,或者request.form.get('name') 如果它是可选的。

You can get request data from

  1. request.form for form data, this includes form and file data,
  2. request.json and request.get_json for JSON data
  3. request.headers for headers
  4. request.args to get query params

They're all like a dictionary, use request.form['name'] if you know the key exists, or request.form.get('name') if it is optional.

坚持沉默 2025-01-19 11:27:51

使用 request.get_json() 获取发布的 JSON 数据。

data = request.get_json()
name = data.get('name', '')

使用 POST 方法提交表单时,使用 request.form 获取数据。

name = request.form.get('name', '')

使用 request.args 获取 URL 查询字符串中传递的数据,就像使用 GET 方法提交表单时一样。

request.args.get("name", "")

request.form 等类似于字典,如果未传递,则使用 get 方法获取默认值。

Use request.get_json() to get posted JSON data.

data = request.get_json()
name = data.get('name', '')

Use request.form to get data when submitting a form with the POST method.

name = request.form.get('name', '')

Use request.args to get data passed in the query string of the URL, like when submitting a form with the GET method.

request.args.get("name", "")

request.form etc. are dict-like, use the get method to get a value with a default if it wasn't passed.

疧_╮線 2025-01-19 11:27:51

导入请求:

from flask import request

URL 查询参数:

name = request.args.get("name")
age = request.args.get("age")

表单输入:

name = request.form.get('name')
age = request.form.get('age')

OR(如果您知道密钥存在,则使用索引,指定输入字段的名称

name = request.form['name']
age = request.form['age']

JSON 数据(对于内容类型 application/json >)

data = request.get_json()

Import request:

from flask import request

URL query parameters:

name = request.args.get("name")
age = request.args.get("age")

Form Input:

name = request.form.get('name')
age = request.form.get('age')

OR (use indexing if you know the key exists, specify the name of input fields)

name = request.form['name']
age = request.form['age']

JSON Data (for content type application/json)

data = request.get_json()
病毒体 2025-01-19 11:27:51

要在不使用 application/json 内容类型的情况下发布 JSON,请使用 request.get_json(force=True)

@app.route('/process_data', methods=['POST'])
def process_data():
    req_data = request.get_json(force=True)
    language = req_data['language']
    return 'The language value is: {}'.format(language)

To get JSON posted without the application/json content type, use request.get_json(force=True).

@app.route('/process_data', methods=['POST'])
def process_data():
    req_data = request.get_json(force=True)
    language = req_data['language']
    return 'The language value is: {}'.format(language)
小猫一只 2025-01-19 11:27:51

要在 JavaScript 中使用 jQuery 发布 JSON,请使用 JSON.stringify 转储数据,并将内容类型设置为 application/json。

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {
        alert("success");
    }   
});

在 Flask 中使用 request.get_json() 解析它。

data = request.get_json()

To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json.

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {
        alert("success");
    }   
});

Parse it in Flask with request.get_json().

data = request.get_json()
流星番茄 2025-01-19 11:27:51

原始数据作为 request.stream 从 WSGI 服务器传递到 Flask 应用程序。流的长度位于 Content-Length 标头中。

length = request.headers["Content-Length"]
data = request.stream.read(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 the Content-Length header.

length = request.headers["Content-Length"]
data = request.stream.read(length)

It is usually safer to use request.get_data() instead.

嘿咻 2025-01-19 11:27:51

以下是发布表单数据以将用户添加到数据库的示例。检查 request.method == "POST" 以检查表单是否已提交。使用 request.form 中的键获取表单数据。否则使用

渲染 HTML 模板。表单中的字段应具有与 request.form 中的键匹配的 name 属性。

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/user/add", methods=["GET", "POST"])
def add_user():
    if request.method == "POST":
        user = User(
            username=request.form["username"],
            email=request.form["email"],
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("index"))

    return render_template("add_user.html")
<form method="post">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="email">Email</label>
    <input type="email" name="email" id="email">
    <input type="submit">
</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 from request.form to get the form data. Render an HTML template with a <form> otherwise. The fields in the form should have name attributes that match the keys in request.form.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/user/add", methods=["GET", "POST"])
def add_user():
    if request.method == "POST":
        user = User(
            username=request.form["username"],
            email=request.form["email"],
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("index"))

    return render_template("add_user.html")
<form method="post">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="email">Email</label>
    <input type="email" name="email" id="email">
    <input type="submit">
</form>
乖乖 2025-01-19 11:27:51

要解析 JSON,请使用 request.get_json()

@app.route("/something", methods=["POST"])
def do_something():
    result = handle(request.get_json())
    return jsonify(data=result)

To parse JSON, use request.get_json().

@app.route("/something", methods=["POST"])
def do_something():
    result = handle(request.get_json())
    return jsonify(data=result)
樱娆 2025-01-19 11:27:51

如果正文被识别为表单数据,它将位于 request.form 中。如果是 JSON,则位于 request.get_json() 中。否则原始数据将位于 request.data 中。如果您不确定如何提交数据,可以使用 or 链来获取第一个包含数据的链。

def get_request_data():
    return (
        request.args
        or request.form
        or request.get_json(force=True, silent=True)
        or request.data
    )

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 in request.get_json(). Otherwise the raw data will be in request.data. If you're not sure how data will be submitted, you can use an or chain to get the first one with data.

def get_request_data():
    return (
        request.args
        or request.form
        or request.get_json(force=True, silent=True)
        or request.data
    )

request.args contains args parsed from the query string, regardless of what was in the body, so you would remove that from get_request_data() if both it and a body should data at the same time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文