1
我有一個Django應用程序,爲tEST設置了REST。Python請求模塊JSON格式
我希望能夠使用REST API更新數據庫。
我可以在命令行上發出一個curl命令來達到我想要的效果(按照tastypie文檔)。
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(有效載荷)將來臨 - 我試過路過只是字典,但有效載荷被添加到querysting在那種情況下,和tastypie抱怨。我試圖將字典格式化爲一個元組,但我不確定它期望的是什麼。
有人可以幫忙嗎(或者我在代碼中看錯了地方)?
完美的作品,謝謝!我沒有注意到「參數」論證從文檔的第一個例子變成了我所看到的「數據」。 –