Python:POST多个Multipart编码文件

1 投票
1 回答
2929 浏览
提问于 2025-04-18 01:44

正如这里所描述的,我们可以通过一次请求发送多个文件:使用Python的requests模块一次上传多个文件

不过,我在从一个列表中生成这些多个文件处理器时遇到了问题。

假设我想像这样发起一个请求:

sendfiles = {'file1': open('file1.txt', 'rb'), 'file2': open('file2.txt', 'rb')}
r = requests.post('http://httpbin.org/post', files=sendfiles)

我该如何从列表 myfiles 中生成 sendfiles 呢?

myfiles = ["file1.txt", "file20.txt", "file50.txt", "file100.txt", ...]

1 个回答

4

可以使用字典推导式,利用 os.path.splitext() 来去掉文件名中的扩展名:

import os.path

sendfiles = {os.path.splitext(fname)[0]: open(fname, 'rb') for fname in myfiles}

注意,使用一个包含两个元素的元组列表也是可以的:

sendfiles = [(os.path.splitext(fname)[0], open(fname, 'rb')) for fname in myfiles]

要小心;如果使用 files 参数发送一个多部分编码的 POST 请求,这样会先把所有文件都读入内存。可以使用 requests-toolbelt 项目 来构建一个流式的 POST 请求体:

from requests_toolbelt import MultipartEncoder
import requests
import os.path

m = MultipartEncoder(fields={
    os.path.splitext(fname)[0]: open(fname, 'rb') for fname in myfiles})
r = requests.post('http://httpbin.org/post', data=m,
                  headers={'Content-Type': m.content_type})

撰写回答