【问题标题】:Python Requests module JSON formatPython 请求模块 JSON 格式
【发布时间】:2012-10-16 15:42:16
【问题描述】:

我有一个 Django 应用程序,为 REST 设置了美味的派。

我希望能够使用 REST API 更新数据库。

我可以在命令行上发出 curl 命令来实现我想要的,(根据美味派文档)。

curl --dump-header - -H "Content-Type: application/json" -X PATCH --data '{"comments": "comment1"}' http://127.0.0.1:8000/api/seq/loadedwith/12092/

HTTP/1.0 202 ACCEPTED
Date: Fri, 26 Oct 2012 11:06:58 GMT
Server: WSGIServer/0.1 Python/2.6.6
Content-Type: text/html; charset=utf-8

所以现在我正在尝试使用请求模块来实现相同的目标。从 python 请求模块获取请求工作,但我无法让补丁或帖子工作。

url='http://127.0.0.1:8000/api/seq/loadedwith/12092/'
headers={'content-type': 'application/json'}
payload={"comments":"comment2"}
requests.patch(url=url, params=json.dumps(payload),  headers=headers)

我得到错误:

  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/requests-0.14.1-py2.7.egg/requests/api.py", line 120, in patch
      return request('patch', url,  data=data, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests-0.14.1-py2.7.egg/requests/safe_mode.py", line 39, in wrapped
      return function(method, url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests-0.14.1-py2.7.egg/requests/api.py", line 51, in request
      return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests-0.14.1-py2.7.egg/requests/sessions.py", line 182, in request
    params=from_key_val_list(params),
  File "/usr/local/lib/python2.7/dist-packages/requests-0.14.1-py2.7.egg/requests/utils.py", line 135, in from_key_val_list
    raise ValueError('cannot encode objects that are not 2-tuples')
ValueError: cannot encode objects that are not 2-tuples

当我添加 json.dumps(payload) 时,这似乎即将到来 - 我尝试只传递字典,但在这种情况下,有效负载被添加到查询字符串中,并且美味派抱怨。我曾尝试将字典格式化为 tuple ,但我不确定它到底期望什么。

有人可以帮忙吗,(或者我在代码中看错地方了)?

【问题讨论】:

    标签: python json encoding python-requests


    【解决方案1】:

    params 应该始终是 dict 或 2 值元组序列,然后为您编码。但是,您想上传已编码的正文,因此您需要 data 关键字:

    requests.patch(url, data=json.dumps(payload), headers=headers)
    

    其实data是第二个参数,所以你甚至可以这样做:

    requests.patch(url, json.dumps(payload), headers=headers)
    

    因为您通常只使用 PATCH 发送不透明数据。 .post().put() 方法的行为方式相同,第二个参数是 data 关键字。

    【讨论】:

    • 完美运行,谢谢!我没有注意到“参数”参数已从文档中的第一个示例更改为我正在查看的示例中的“数据”。
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多