我正在尝试将字典(字符串)列表传递给放置请求。我收到此错误:
TypeError:POST数据应为字节,可迭代的字节。
这是使用python
中的词典(字符串)列表发出请求的正确方法。
列表如下所示:
list1 = ['{"id" : "","email" : "[email protected]","fullName": "John Lorang"}', '{"id" : "","email" : "[email protected]","fullName": "Lola Dsilva"}']
myData = json.dumps(list1)
myRestRequestObj = urllib.request.Request(url,myData)
myRestRequestObj.add_header('Content-Type','application/json')
myRestRequestObj.add_header('Authorization','Basic %s')
myRestRequestObj.get_method = lambda : 'PUT'
try:
myRestRequestResponse = urllib.request.urlopen(myRestRequestObj)
except urllib.error.URLError as e:
print(e.reason)
我想您可以使用requests
模块(pip install requests
)。
requests是用于Python的简单但功能强大的HTTP库。
import json
import requests
my_data = json.dumps(list1)
headers = {
'Authorization': 'Basic {token}'.format(token=your_token)
}
response = requests.put(url, headers=headers, json=my_data)
print("Status code: {status}".format(status=response.status_code))
print("raw response: {raw_response}".format(
raw_response=response.text
)
print("json response: {json_response}".format(
json_response=response.json()
)