当我尝试通过python请求发送带有文件的POST请求时出现错误

问题描述 投票:0回答:0

我尝试发送 POST 请求,其中包含普通数据和图像文件。 代码:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = 'http://localhost:8000/films/'
data = {
    'title': 'test title', 
    'poster_name': 'test name', 
    'rating': '10.00', 
    'imdb_id': 'tt1375666dfs', 
    'country': 'test country', 
    'release_date': '12/03/2023', 
    'director': 'test director', 
    'description': 'Test description', 
    'age_restriction': '18', 
    'studio': 'Test studio',
    'screenshots': [
       ('screenshot1', ('pic.png', open('pic.png', 'rb'), 'image/png')),
       ('screenshot2', ('pic2.png', open('pic2.png', 'rb'), 'image/png')),
    ]
}

encoder = MultipartEncoder(fields=data)

headers = {'Content-Type': encoder.content_type}

response = requests.post(url, data=encoder, headers=headers)

print(response.status_code)
print(response.json())

错误:“TypeError: expected string or bytes-like object.”我做错了什么?

python file http post request
© www.soinside.com 2019 - 2024. All rights reserved.