简体   繁体   中英

How can i send file with aiohttp?

this is my code:

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

and I want to send file with aiohttp to URL but I got this exception

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

I do that with requests library like this

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

but I decided to use aiohttp because it shoud be async please help me for this decision

thanks

you need to serialize payload data using data= b'form' eg

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

By default session uses python's standard json module for serialization. But it is possible to use different serializer. ClientSession accepts json_serialize parameter. Then you dont need to explicitly serialize your payload.

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()
    ....
  • Warning: above code is not tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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