Python:发布多个多部分编码的文件

2024-05-14 08:45:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如这里所述,可以通过一个请求发送多个文件: Uploading multiple files in a single request using python requests module

但是,我在从列表生成这些多个文件处理程序时遇到了一个问题。 所以假设我想提出这样的请求:

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

如何从列表myfiles生成sendfiles?在

^{pr2}$

Tags: 文件intxt列表filesopenmultiplepost
1条回答
网友
1楼 · 发布于 2024-05-14 08:45:32

使用字典理解,使用^{}从文件名中删除这些扩展名:

import os.path

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

请注意,2项元组的列表也可以:

^{pr2}$

注意:使用files参数发送一个多部分编码的POST将首先将所有这些文件读入内存。使用^{} project生成流式文章正文:

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})

相关问题 更多 >

    热门问题