【问题标题】:Sending a JSON string as a post request发送 JSON 字符串作为 post 请求
【发布时间】:2016-03-28 19:15:31
【问题描述】:

rocksteady 的解决方案奏效了

他最初确实提到了字典。但是以下发送 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)

我正在使用一个 API,该 API 要求我将 JSON 作为 POST 请求发送以获取结果。问题是 Python 3 不允许我这样做。

以下 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)

但是,在 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)

我已经尝试过urlencode(),就像你应该做的那样。但这会从 Web 服务器返回 400 状态代码,因为它需要纯 JSON。即使纯 JSON 数据无效,我也需要以某种方式强制 Python 发送它。

编辑:根据要求,这是我得到的错误。由于这是一个烧瓶应用程序,这里是调试器的屏幕截图:

Screenshot

添加 .encode('utf-8') 会给我一个“预期的字符串或缓冲区”错误

EDIT 2:添加了.encode('utf-8') 的调试器的Screenshot

【问题讨论】:

  • 你不是“应该”使用 urlencode;这是针对表单编码数据的,但您发送的是 JSON。但如果你遇到错误,你应该发布它。
  • 服务器不支持 unicode 字符“\u2119”。如果想测试另一个,请创建一个演示服务器。
  • 看看这个:json.dumps vs. flask.jsonify也许有帮助。
  • 您发布的错误是没有.encode('utf-8') 调用。它有什么错误?
  • @rocksteady 这看起来很有趣。但是我尝试手动设置内容标题没有运气,它给出了相同的错误。此代码也没有导入烧瓶。这是一个烧瓶应用程序正在使用的模块 - 我会继续研究这个,我可能错过了与内容标题相关的一些内容

标签: python json http python-3.x


【解决方案1】:

由于我有一个类似的应用程序正在运行,但客户端仍然丢失,我自己尝试了一下。 正在运行的服务器来自以下练习:

Miguel Grinberg - designing a restful API using Flask

这就是它使用身份验证的原因。

有趣的部分:使用requests,您可以保持字典不变。

看看这个:

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

它似乎工作:)

更新 1:

POST 请求是使用 requests.post(...) 这在这里描述得很好:python requests

更新 2:

为了完成答案:

requests.post("http://127.0.0.1:5000/api/v1.0/projects", json=content)

发送 json 字符串。

json是请求的有效参数,内部使用json.dumps()...

【讨论】:

  • 字典不是问题。这些工作正常,我无法发送不属于任何字典或列表的单个 JSON 字符串。但也可以使用字符串测试请求,因为您建议这样做。
猜你喜欢
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多