python - 如何在 python 下使用请求发出文件请求?
问题描述
我已经提出了一个帖子请求,multipart/form-data; boundary=a1c2469c-2a1f-48e6-8f1d-311f8650c855
我得到了这个
POST /api/feed/upload-resource HTTP/1.1
App-Id: 15762288
Version-Name: 3.26.0.451
User-Agent: Right-Android/3.26.0.451
Content-Type: multipart/form-data; boundary=a1c2469c-2a1f-48e6-8f1d-311f8650c855
Content-Length: 75412
Connection: Keep-Alive
Accept-Encoding: gzip
--a1c2469c-2a1f-48e6-8f1d-311f8650c855
Content-Disposition: form-data; name="h"
Content-Length: 4
1080
--a1c2469c-2a1f-48e6-8f1d-311f8650c855
Content-Disposition: form-data; name="w"
Content-Length: 4
1080
--a1c2469c-2a1f-48e6-8f1d-311f8650c855
Content-Disposition: form-data; name="image"; filename="/storage/emulated/0/Android/data/com.xiaoyu.rightone/tiny/tiny-738-2018-08-03-15-32-53.jpg"
Content-Type: text/plain
Content-Length: 74910
如果我想使用 Python requests 包模拟这个请求,我该怎么做。
我已经检查了文档,并且尝试过像这样使用文件参数
with open(path, 'rb') as f:
files = {
"h": "1495",
"w": "840",
"filename": ("image", f.read()),
}
r = requests.post(url, files=files)
但是,在我的情况下,我总是收到类似upload_resource_empty
.
解决方案
这应该有效:
import requests
files = {
'image': ('file_name.jpg', open('file.jpg', 'rb'), 'text/plain'),
'w': (None, '123'),
'h': (None, '222')
}
response = requests.post('url', files=files)
字典中的元组具有以下格式:('filename', fileobj, 'content_type', custom_headers)
推荐阅读
- python - 如果 sql 有日期条件,pyodbc 结果返回空
- javascript - 触发缓存以确保数据正确问题 - swr 挂钩 - next.js(使用打字稿)
- webix - 带有水平滚动条的树表
- java - 如果连接丢失,我想显示以前的数据而不是空列表
- docker - docker run --entrypoint "python /path/to/file.py" 导致“没有这样的文件或目录:未知。” 错误
- python - 如何在我的 Django+drf-yasg 项目中使用 editor.swagger.io 中的 swagger.json?
- ubuntu - 在 ubuntu linux 中以 root 权限运行 VS Code 不再起作用
- python - 来自分组数据的 2×2 热图矩阵可视化
- angular - 为什么值不更新?
- javascript - 如何从最高到最低列出点?