如何用Python将InMemoryUploadedFile通过requests发送请求并获取200状态?
问题描述
我在Postman中按如下方式发送数据:
我的Python代码如下:
headers = { "Accept": "*/*", "Content-Type": "multipart/form-data; boundary=974767299852498929531610575", } response = requests.request( "POST", LINK, headers=headers, data={ 'product_id': 1, 'product_images': [file, ] } )
其中file为InMemoryUploadedFile格式,但请求报错。我还尝试了:
file = my_file.file.getvalue()
但仍然报错。请问如何修改代码以获取200状态码?有什么解决思路吗?
解决方法及思路
不要手动设置
Content-Type头requests库会自动处理multipart/form-data请求的边界值和Content-Type头,手动指定边界值会导致请求格式不匹配,直接删除自定义的Content-Type配置。使用
files参数上传文件
发送文件时不能把文件放在data参数里,要改用files参数。针对你的场景,代码可修改为:headers = { "Accept": "*/*" } # 构造files参数,非文件字段用None作为文件名占位 files = { 'product_id': (None, '1'), 'product_images': (my_file.name, my_file, my_file.content_type) } response = requests.post(LINK, headers=headers, files=files)若需上传多个文件,
product_images可写成列表形式:files = { 'product_id': (None, '1'), 'product_images': [ (file1.name, file1, file1.content_type), (file2.name, file2, file2.content_type) ] }正确处理
InMemoryUploadedFile
无需调用getvalue()转成字节流,直接将InMemoryUploadedFile对象传入files参数即可,requests会自动处理文件读取逻辑。调试建议
- 打印
response.text或response.json()查看后端返回的具体错误信息,明确问题根源 - 对比Postman的Raw请求内容与
requests发送的请求,通过print(response.request.headers)和print(response.request.body)检查格式差异
- 打印
内容的提问来源于stack exchange,提问作者Anna Berezko
相关产品推荐
相关产品推荐

