TypeError:POST数据应该是字节、字节的iterable或file对象。在python中尝试传递PUT请求时,它不能是str类型

2024-04-26 09:57:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将字典(字符串)列表传递给一个请求put的。我得到这个错误:

TypeError: POST data should be bytes, an iterable of bytes.

这是用python中的字典(字符串)列表发出put请求的正确方法。你知道吗

列表如下所示:

list1 = ['{"id" : "","email" : "John@fullcontact.com","fullName": "John Lorang"}', '{"id" : "","email" : "Lola@fullcontact.com","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)

Tags: 字符串comid列表字典bytesputemail
2条回答

我假设您可以使用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()
)

正如您在评论中所说的,您不能使用请求(听到这个消息很难过!),所以我用urllib做了另一个片段(简短的回答:您必须.encode('utf-8')json.dumpsdecode('utf-8')response.read()):

import urllib.request
import urllib.error
import json

url = 'http://httpbin.org/put'
token = 'jwtToken'

list1 = ['{"id" : "","email" : "John@fullcontact.com","fullName": "John Lorang"}', '{"id" : "","email" : "Lola@fullcontact.com","fullName": "Lola Dsilva"}']

# Request needs bytes, so we have to encode it
params = json.dumps(list1).encode('utf-8')
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Basic {token}'.format(token=token)
}

# Let's try to create our request with data, headers and method
try:
    request = urllib.request.Request(url, data=params, headers=headers, method='PUT')
except urllib.error.URLError as e:
    # Unable to create our request, here the reason
    print("Unable to create youro request: {error}".format(error=str(e)))
else:
    # We did create our request, let's try to use it
    try:
        response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as e:
        # An HTTP error occured, here the reason
        print("HTTP Error: {error}".format(error=str(e)))
    except Exception as e:
        # We got another reason, here the reason
        print("An error occured while trying to put {url}: {error}".format(
            url=url,
            error=str(e)
        ))
    else:
        # We are printing the result
        # We must decode it because response.read() returns a bytes string
        print(response.read().decode('utf-8'))

我确实试着添加一些评论。我希望这个解决方案对你有帮助!你知道吗

为了帮助您更好地学习python,您应该阅读Style Guide for Python Code

相关问题 更多 >