繁体   English   中英

如何使用 aiohttp 发送文件?

[英]How can i send file with aiohttp?

这是我的代码:

payload = {'text': input_text,
           'question_info': '',
           'include_intonation': 1,
           'stress_version': stress_version,
           'include_fluency': 1,
           'include_ielts_subscore': 1}

files = [
    ('user_audio_file', open(saved_file_path, 'rb'))
]
headers = {}
form = aiohttp.FormData()
for key, value in payload.items():
    form.add_field(key, value)
form.add_field('user_audio_file', open(saved_file_path, 'rb'))
async with aiohttp.ClientSession() as session:
    async with session.post(url,data=form) as response:
        response_json = await response.json()

我想将带有 aiohttp 的文件发送到 URL 但我遇到了这个异常

'Can not serialize value type: <class \'int\'> headers: {} value: 1'

我用这样的请求库来做到这一点

response = request(
    "POST", url, headers=headers, data=payload, files=files)
response_json = response.json()

但我决定使用 aiohttp 因为它应该是异步的,请帮助我做出这个决定

谢谢

您需要使用data= b'form'序列化有效负载数据,例如

async with aiohttp.ClientSession() as session:
    async with session.post(url,data=b'form') as response:
        response_json = await response.json()

默认情况下,会话使用 python 的标准 json 模块进行序列化。 但是可以使用不同的序列化程序。 ClientSession 接受 json_serialize 参数。 然后您不需要显式序列化您的有效负载。

import ujson
    async with aiohttp.ClientSession(
            json_serialize=ujson.dumps) as session:
        await session.post(url,data=form) as response:
            response_json = await response.json()
    ....
  • 警告:以上代码未经测试。

暂无
暂无

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

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