繁体   English   中英

使用 aiohttp 从 Python 中的 memory 上传多部分/表单数据

[英]Upload multipart/form-data from memory in Python with aiohttp

我正在尝试使用 Discord.py 将附件上传到 Ballchasing 的 API。 以下是相关的 API 部分:

https://discordpy.readthedocs.io/en/latest/api.html#discord.Attachment.read

https://ballchasing.com/doc/api#upload-upload-post

文档中的示例建议使用请求,但我一遍又一遍地阅读,这不是 Discord 机器人的最佳实践,因为您希望异步代码避免任何可能阻止脚本执行的事情。

这是我所拥有的:

@commands.Cog.listener()        
async def on_message(self, message):
    headers = {'Authorization':self.upload_key_bc}
    for attachment in message.attachments:
        file = io.BytesIO(await attachment.read())
        action = {'file': ('replay.replay', file.getvalue())}
        async with aiohttp.ClientSession() as session:
            async with session.post(self.api_upload_bc, headers=headers, data=action) as response:
                print(response.status)
                print(await response.text())

我收到以下回复:

failed to get multipart form: request Content-Type isn't multipart/form-data

我尝试将 Content-Type header 强制为 multiparth/form-data ,但出现不同的错误:

failed to get multipart form: no multipart boundary param in Content-Type

我认为我发送数据的方式是问题所在。 我错过了什么?

手动创建FormData object 并明确指定文件名以启用 multipart/form-data。

如果深入代码, {'file': ('replay.replay', file.getvalue())}FormData中被视为非特殊值并呈现为str(('replay.replay', file.getvalue())urllib.parse.urlencode()中。

from aiohttp import FormData

@commands.Cog.listener()
async def on_message(self, message):
    headers = {'Authorization': self.upload_key_bc}
    for attachment in message.attachments:
        
        formdata = FormData()
        formdata.add_field('file', BytesIO(await attachment.read()), filename='replay.replay')

        async with aiohttp.ClientSession() as session:
            async with session.post(self.api_upload_bc, headers=headers, data=formdata) as response:
                print(response.status)
                print(await response.text())

为了将其转换为多部分/表单数据,必须将文件添加为io.IOBase object,或者您必须使用带有特定修饰符的add_field 查看FormData下的文档。 https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.FormData

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM