我想能够获得数据发送到我的Flask应用程序。我已经尝试访问请求。数据,但它是一个空字符串。如何访问请求数据?

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头,这是关于获取原始数据而不是解析数据。


当前回答

我只是面对同样的需求。我必须保存信息以备不时之需。所以,我使用下面的公式:

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

Repr (request)将给出基本信息的字符串表示。你可以添加用户代理数据: request.headers.get(“用户代理”)

我还保存会话大陆,因为它可能包含有价值的信息

其他回答

文档描述了请求期间请求对象(来自flask import request)上可用的属性。在大多数情况下请求。Data将为空,因为它被用作备用数据:

请求。data包含传入的请求数据作为字符串,以防它与mimetype Flask不处理。

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.

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

请求。Form ['name']:如果知道键存在,则使用索引 Request.form.get ('name'):如果键可能不存在,则使用get Request.form.getlist ('name'):如果键被发送多次,并且你想要一个值列表,请使用getlist。Get只返回第一个值。

下面是一个解析发布的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:

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

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

使用请求。当使用POST方法提交表单时,表单可以获取数据。

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

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

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

请求。Form等是dict-like的,如果没有传递,使用get方法来获得一个默认值。

在使用HTML表单发布表单数据时,请确保输入标记具有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输入有名称,所以它是request.form中唯一的键。

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

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