gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:42 25 4
gpt4 key购买 nike

如此处所述,可以通过一个请求发送多个文件: 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

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

最佳答案

使用字典理解,使用 os.path.splitext()从文件名中删除这些扩展名:

import os.path

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

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

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

当心;使用 files 参数发送多部分编码的 POST 首先将所有这些文件读入内存。使用 requests-toolbelt project改为构建流式 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})

关于Python:发布多个多部分编码的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22918916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com