TypeError:POST数据应为字节,字节可迭代或文件对象。尝试在python

问题描述 投票:0回答:1
中传递PUT请求时,它不能为str类型。

我正在尝试将字典(字符串)列表传递给放置请求。我收到此错误:

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)
python urllib put
1个回答
0
投票

我想您可以使用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()
)
© www.soinside.com 2019 - 2024. All rights reserved.