这是我的代码:
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,因为它应该是异步的,请帮助我做出这个决定。
谢谢
发布于 2021-10-27 20:09:48
您需要使用data= b'form'序列化有效负载数据,例如
async with aiohttp.ClientSession() as session:
async with session.post(url,data=b'form') as response:
response_json = await response.json()默认情况下,session使用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()
....更新我尝试设置一个本地http服务器并上传一个json。我正在克服你的错误,并能够上传数据。您是否使用b'form'序列化表单数据
根据这个GitHub issue discussion,我们需要asyncio来控制异步事件循环,并通过函数执行异步/等待。
以下是相关代码。
async def uploadForm():
async with aiohttp.ClientSession() as session:
async with session.post(url,data=b'form') as response: #Converting form to binary payload using b'form'
response_json = await response.json(content_type='text/html')
print(response_json)
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(uploadForm())
loop.close()
if __name__ == '__main__':
main()希望这对你有帮助。
https://stackoverflow.com/questions/69744818
复制相似问题