获取烧瓶请求中收到的数据

问题:获取烧瓶请求中收到的数据

我希望能够将数据发送到我的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.


回答 0

文档描述的要求提供的属性。在大多数情况下,request.data由于它用作后备广告,因此将为空:

request.data 如果传入的请求数据带有mimetype Flask无法处理,则将其包含为字符串。

  • request.args:URL查询字符串中的键/值对
  • request.form:正文中的键/值对,来自HTML帖子形式或非JSON编码的JavaScript请求
  • request.files:Flask与正文分开的正文文件form。必须使用HTML表单,enctype=multipart/form-data否则将不会上传文件。
  • request.values:组合argsformargs如果键重叠则首选
  • request.json:解析的JSON数据。该请求必须具有application/json内容类型,或用于request.get_json(force=True)忽略内容类型。

所有这些都是MultiDict实例(除外json)。您可以使用以下方法访问值:

  • request.form['name']:如果您知道密钥存在,请使用索引
  • request.form.get('name')get如果密钥可能不存在,则使用
  • request.form.getlist('name')getlist如果键被多次发送并且需要值列表,则使用该键。get仅返回第一个值。

The docs describe the attributes available on the 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.

回答 1

要获取原始数据,请使用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

回答 2

对于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')

对于以内容类型发布的JSON application/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()

回答 3

这是解析发布的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

或使用邮递员:

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:


回答 4

如果您发布内容类型为的JSON,请在Flask中application/json使用request.get_json()它。如果内容类型不正确,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()

回答 5

要获取原始帖子正文,而不管内容类型如何,请使用request.get_data()。如果使用request.data,它将调用request.get_data(parse_form_data=True),它将填充request.form MultiDictdata留空。

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.


回答 6

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"
}

回答 7

使用request.get_json()得到张贴JSON数据。

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

使用request.formPOST方法提交表单时用于获取数据。

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

使用request.args得到的网址,用GET方法提交表单的时候喜欢的查询字符串传递的数据。

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

request.form等类似dict,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.


回答 8

要发布不包含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)

回答 9

原始数据从WSGI服务器传递到Flask应用程序request.stream。流的长度在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.


回答 10

要在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()

回答 11

要解析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)

回答 12

这是一个发布表单数据以将用户添加到数据库的示例。检查request.method == "POST"表单是否已提交。使用键request.form来获取表单数据。使用<form>其他方式呈现HTML模板。表单中的字段应具有name与中的键匹配的属性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>

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>

回答 13

如果内容类型被识别为表单数据,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.


回答 14

如果将正文识别为表单数据,它将在中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包含从查询字符串中解析出的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.


回答 15

使用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.