TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str while trying to pass PUT request in python

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str while trying to pass PUT request in python

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

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

这是使用 python 中的字典(字符串)列表发出放置请求的正确方法吗?

列表如下所示:

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)

我假设您可以使用 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.dumps 并且decode('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