发布到Flask与Postman与请求填充不同的请求属性 [英] Posting to Flask with Postman versus requests populates different request attributes

查看:963
本文介绍了发布到Flask与Postman与请求填充不同的请求属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发送一个POST请求到我的Flask应用程序与Postman和请求库。当我使用Postman时,我可以通过 json.loads(request.data)获取数据。当我使用请求或curl,我可以获得与 request.form 的数据。为什么要使用两个工具填充不同的属性来发送相同的数据?

I'm sending a POST request to my Flask app with Postman and also the requests library. When I use Postman, I can get the data with json.loads(request.data). When I use requests or curl, I can get the data with request.form. Why does sending the same data with the two tools populating different attributes?

推荐答案

您已经使用Postman以JSON格式发送数据,并且您已使用请求和curl将其作为表单数据发送。你可以告诉程序发送数据的任何你期望的,而不是让它使用其默认。例如,您可以发送带有请求的JSON:

You've used Postman to send the data as JSON, and you've used requests and curl to send it as form data. You can tell either program to send the data as whatever you expect, rather than letting it use its "default". For example, you can send JSON with requests:

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

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

Also note that you can get the JSON directly from the Flask request, without loading it yourself:

from flask import request
data = request.get_json()






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


request.data holds the body of the request, whatever format it may be. Common types are application/json and application/x-www-form-urlencoded. If the content type was form-urlencoded, then request.form will be populated with the parsed data. If it was json, then request.get_json() will access it instead.

如果你真的不知道你是以表单还是以JSON格式获取数据,你可以写一个简短的函数来尝试使用一个如果这不工作使用其他。

If you're really not sure if you'll get the data as a form or as JSON, you could write a short function to try to use one and if that doesn't work use the other.

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

这篇关于发布到Flask与Postman与请求填充不同的请求属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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