Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用aiohttp从Python内存上载多部分/表单数据_Python_Discord.py_Multipartform Data_Aiohttp - Fatal编程技术网

使用aiohttp从Python内存上载多部分/表单数据

使用aiohttp从Python内存上载多部分/表单数据,python,discord.py,multipartform-data,aiohttp,Python,Discord.py,Multipartform Data,Aiohttp,我正在尝试使用Discord.py将附件上载到Ballchasing的API。以下是API的相关章节: 文档中的示例建议使用请求,但我已反复阅读,这不是Discord bot的最佳实践,因为您希望异步代码避免任何可能阻止脚本执行的事情 以下是我所拥有的: @commands.Cog.listener() _消息上的异步定义(self,message): headers={'Authorization':self.upload\u key\u bc} 对于message.attachments

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

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

以下是我所拥有的:

@commands.Cog.listener()
_消息上的异步定义(self,message):
headers={'Authorization':self.upload\u key\u bc}
对于message.attachments中的附件:
file=io.BytesIO(等待attachment.read())
操作={'file':('replay.replay',file.getvalue())}
与aiohttp.ClientSession()作为会话异步:
与session.post(self.api\u upload\u bc,headers=headers,data=action)异步作为响应:
打印(响应状态)
打印(等待响应。text())
我得到的回应是:

failed to get multipart form: request Content-Type isn't multipart/form-data
我尝试将内容类型标题强制为多路径/表单数据,但得到了不同的错误:

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

我认为我发送数据的方式是个问题。我缺少什么?

为了将其转换为多部分/表单数据,必须将文件添加为
io.IOBase
对象,或者必须使用带有特定修饰符的
add\u字段。查看
FormData
下的文档

手动创建
FormData
对象,并明确指定文件名以启用多部分/表单数据

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


这个很好用,谢谢。
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())