![](/img/trans.png)
[英]Python: POST request status code 200 not allowing json conversion
[英]Python json POST request status 200 while expecting status 201
我正在嘗試向Web服務器發出POST請求,以嘗試創建新資源。 我對要在服務器上進行通信的Python和平台都不太熟悉,所以我不確定這是否是我的python技能需要更多的練習,或者我是否只是未正確提交請求到服務器。 這是我的代碼:
import requests
apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"
values = """
{
"clientId": 1,
"method": 3,
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 10,
"note": "",
"invoiceIds": []
}
"""
headers = {
'X-Auth-App-Key': apiKey,
'Content-Type': 'application/json'
}
r = requests.post(serverUrl, data=values, headers=headers)
r
服務器以響應200(確定)消息進行響應,但是由於我嘗試創建新資源,因此服務器應以響應201(已創建)消息進行響應。 有什么想法我做錯了嗎?
嘗試使用https://
,
更改serverUrl = "http://192.168.0.5/api/v1.0/payments"
至
serverUrl = "https://192.168.0.5/api/v1.0/payments"
這可能不會導致不同的HTTP狀態代碼,但是您可以使用json
參數直接將JSON編碼的字典發送給request.post requests.post()
。 因此, values
可以是字典, requests
將設置內容類型,因此您無需在headers
:
values =
{
"clientId": 1,
"method": 3,
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 123.45,
"note": "",
"invoiceIds": []
}
headers = {'X-Auth-App-Key': apiKey}
r = requests.post(serverUrl, json=values, headers=headers)
只是有點清潔。
關於預期的201響應,是否實際創建了資源? 使用其他工具(例如curl
時,您是否收到201響應?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.