获取 Flask 请求中收到的数据 [英] Get the data received in a Flask request

查看:46
本文介绍了获取 Flask 请求中收到的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将数据发送到我的 Flask 应用程序.我试过访问 request.data 但它是一个空字符串.您如何访问请求数据?

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

<小时>

这个问题的答案让我问在 Python Flask 中获取原始 POST 正文,而不管 Content-Type 标头如何,接下来是关于获取原始数据而不是解析后的数据.


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.

推荐答案

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

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 包含传入的请求数据作为字符串,以防它带有 Flask 无法处理的 mimetype.

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

  • request.args:关键URL 查询字符串中的/value 对
  • request.form:关键正文中的/value 对,来自 HTML 帖子表单或非 JSON 编码的 JavaScript 请求
  • request.files:文件在主体中,Flask 将其与 form 分开.HTML 表单必须使用 enctype=multipart/form-data 否则文件将不会上传.
  • request.values:组合argsform,如果键重叠,则首选 args
  • request.json:解析的 JSON数据.请求必须具有 application/json 内容类型,或使用 request.get_json(force=True) 忽略内容类型.
    • 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).您可以使用以下方法访问值:

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

      • request.form['name']:如果您知道密钥存在,则使用索引
      • request.form.get('name'):如果key可能不存在,使用get
      • request.form.getlist('name'):如果密钥被多次发送并且您想要一个值列表,请使用 getlist.get 只返回第一个值.
      • 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.

      这篇关于获取 Flask 请求中收到的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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