【问题标题】:Posting to Flask with Postman versus requests populates different request attributes使用 Postman 与请求发布到 Flask 填充不同的请求属性
【发布时间】:2015-07-20 13:59:11
【问题描述】:

我正在使用 Postman 以及 requests 库向我的 Flask 应用程序发送 POST 请求。当我使用 Postman 时,我可以使用json.loads(request.data) 获取数据。当我使用 requests 或 curl 时,我可以使用request.form 获取数据。为什么使用填充不同属性的两个工具发送相同的数据?

【问题讨论】:

    标签: python curl flask python-requests postman


    【解决方案1】:

    您使用 Postman 将数据作为 JSON 发送,并且使用 requests 和 curl 将其作为表单数据发送。您可以告诉任一程序按照您的期望发送数据,而不是让它使用其“默认值”。例如,您可以发送带有请求的 JSON:

    import requests
    requests.post('http://example.com/', json={'hello': 'world'})
    

    另外请注意,您可以直接从 Flask 请求中获取 JSON,而无需自己加载:

    from flask import request
    data = request.get_json()
    

    request.data 保存请求的主体,无论它可能是什么格式。常见的类型是application/jsonapplication/x-www-form-urlencoded。如果内容类型为form-urlencoded,则request.form 将填充解析的数据。如果是json,则request.get_json() 将改为访问它。


    如果您真的不确定是以表单还是 JSON 格式获取数据,您可以编写一个简短的函数来尝试使用其中一个,如果不起作用,请使用另一个。

    def form_or_json():
        data = request.get_json(silent=True)
        return data if data is not None else request.form
    
    # in a view
    data = form_or_json()
    

    【讨论】:

      【解决方案2】:

      我希望http://werkzeug.pocoo.org/docs/0.10/wrappers/#werkzeug.wrappers.Request 的这句话能解释它:

      数据 调用 get_data() 和 set_data() 的描述符。这不应该被使用,最终会被弃用。

      【讨论】:

      • 我的问题是为什么我在使用 POSTMAN 时需要使用request.data,因为request.form 不起作用。?我需要保持一致性。我该怎么做?
      猜你喜欢
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2017-01-28
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多