Python 发送 JSON 字符串作为 post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34417279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending a JSON string as a post request
提问by Quad
rocksteady's solution worked
Rocksteady 的解决方案奏效了
He did originally refer to dictionaries. But the following code to send the JSON string also worked wonders using requests:
他最初确实参考了字典。但是以下发送 JSON 字符串的代码也使用请求创造了奇迹:
import requests
headers = {
'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"
content = json.dumps({'bucketId': bucket_id})
r = requests.post(url, data = content, headers = headers)
I'm working with an API that requires me to send JSON as a POST request to get results. Problem is that Python 3 won't allow me to do this.
我正在使用一个 API,它要求我将 JSON 作为 POST 请求发送以获取结果。问题是 Python 3 不允许我这样做。
The following Python 2 code works fine, in fact it's the official sample:
下面的 Python 2 代码工作正常,实际上它是官方示例:
request = urllib2.Request(
api_url +'/b2api/v1/b2_get_upload_url',
json.dumps({ 'bucketId' : bucket_id }),
headers = { 'Authorization': account_authorization_token }
)
response = urllib2.urlopen(request)
However, using this code in Python 3 only makes it complain about data being invalid:
但是,在 Python 3 中使用此代码只会让它抱怨数据无效:
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode
# -! Irrelevant code has been cut out !-
headers = {
'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"
# Tested both with encode and without
content = json.dumps({'bucketId': bucket_id}).encode('utf-8')
request = Request(
url=url,
data=content,
headers=headers
)
response = urlopen(req)
I've tried doing urlencode()
, like you're supposed to. But this returns a 400 status code from the web server, because it's expecting pure JSON. Even if the pure JSON data is invalid, I need to somehow force Python into sending it.
我试过做urlencode()
,就像你应该做的那样。但这会从 Web 服务器返回 400 状态代码,因为它期待纯 JSON。即使纯 JSON 数据无效,我也需要以某种方式强制 Python 发送它。
EDIT: As requested, here are the errors I get. Since this is a flask application, here's a screenshot of the debugger:
编辑:根据要求,这里是我得到的错误。由于这是一个烧瓶应用程序,这是调试器的屏幕截图:
Adding .encode('utf-8')
gives me an "Expected string or buffer" error
添加.encode('utf-8')
给我一个“预期的字符串或缓冲区”错误
EDIT 2: Screenshotof the debugger with .encode('utf-8')
added
编辑 2:添加了调试器的屏幕截图.encode('utf-8')
采纳答案by rocksteady
Since I have a similar application running, but the client still was missing, I tried it myself. The server which is running is from the following exercise:
由于我有一个类似的应用程序正在运行,但客户端仍然丢失,我自己尝试了一下。正在运行的服务器来自以下练习:
Miguel Grinberg - designing a restful API using Flask
Miguel Grinberg - 使用 Flask 设计一个宁静的 API
That's why it uses authentication.
这就是它使用身份验证的原因。
But the interesting part: Using requests
you can leave the dictionary as it is.
但有趣的部分是:使用requests
你可以让字典保持原样。
Look at this:
看这个:
username = 'miguel'
password = 'python'
import requests
content = {"title":"Read a book"}
request = requests.get("http://127.0.0.1:5000/api/v1.0/projects", auth=(username, password), params=content)
print request.text
It seems to work :)
它似乎工作:)
Update 1:
更新 1:
POST requests are done using requests.post(...) This here describes it well : python requests
POST 请求是使用 requests.post(...) 完成的,这里描述得很好:python requests
Update 2:
更新 2:
In order to complete the answer:
为了完成答案:
requests.post("http://127.0.0.1:5000/api/v1.0/projects", json=content)
sends the json-string.
发送 json 字符串。
json
is a valid parameter of the request and internally uses json.dumps()
...
json
是请求的有效参数,内部使用json.dumps()
...