我有一个为 REST 设置了美味派的 Django 应用程序。
我希望能够使用 REST API 更新数据库。
我可以在命令行上发出 curl 命令来实现我想要的,(根据 sweetpie 文档)。
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 ,但我不确定它到底期望什么。
有人可以帮忙吗(或者我在看代码中的错误位置)?