pyhton requests模塊post方法傳參爲多層字典時,轉換錯誤,
如,表單傳參
{
“a”:1,
“b”:{
“A”:2,
“B”:3
}
}post請求後看到form data是:
a:1
b:A
b:B
- 查看官方文檔:
More complicated POST requests
Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made:payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
r = requests.post(“http://httpbin.org/post“, data=payload)
print(r.text)
{
…
“form”: {
“key2”: “value2”,
“key1”: “value1”
},
…
}
這裏說post傳入的dict類型參數會被自動轉化爲form-encoded,查看請求後,這裏的demo是一個一層的字典。多層字典傳輸的時候,確實會異常。
解決辦法:
將第二層字典轉化爲json,json.dumps({“A”:2,”B”:3}),然後賦給b。