aiohttp 异步http请求-2.post 请求application/json和application/x-www-form-urlencode

网友投稿 585 2022-09-06


aiohttp 异步http请求-2.post 请求application/json和application/x-www-form-urlencode

前言

aio发送post请求,body类型的常见的类型传参:

application/jsonapplication/x-请求接口报文示例,Content-Type类型是application/json

POST /api/v1/login/ HTTP/1.1Accept: application/json, */*Accept-Encoding: gzip, deflateConnection: keep-aliveContent-Length: 42Content-Type: application/jsonHost: 127.0.0.1:8000User-Agent: HTTPie/1.0.3{ "password": "123456", "username": "test"}

于是可以使用ClientSession.post()接受 json参数

import aioasyncioasync def main(): async with aioas session: body = { "password": "123456", "username": "test" } async with session.post('/api/v1/login', json=body) as resp: print(resp.url) print(await resp.text())loop = asyncio.get_event_loop()loop.run_until_complete(main())

运行结果

0, "msg": "login success!", "username": "test", "token": "ff7b608ed22407a4cd4d2f7beb1bfe9015574bdc"}

默认情况下,会话使用 python 的标准json模块进行序列化。但可以使用不同的 serializer.

ClientSession接受json_serialize 参数:

import ujsonasync with aio json_serialize=ujson.dumps) as session: await session.post(url, json={'test': 'object'})

笔记:ujson 比json快,但有些不兼容

JSON 响应内容

有一个内置的 JSON 解码器,以防您处理 JSON 数据:

async with session.post('/api/v1/login', json=body) as resp: print(await resp.json())

如果json解码失败,会抛出异常ContentTypeError

raise ContentTypeError(aio0, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8'

使用​​.json()​​解码器后,会将返回的内容解析成python里面的dict类型,方便取值

async with session.post('/api/v1/login', json=body) as resp: res = await resp.json() token = res['token'] print('token: ', token)

application/x-请求接口报文示例,Content-Type类型是application/x-/api/v4/login HTTP/1.1Content-Length: 29Content-Type: application/x-aioasyncioasync def main(): async with aioas session: body = { "password": "123456", "username": "test" } async with session.post('/api/v4/login', data=body) as resp: print(await resp.json()) loop = asyncio.get_event_loop()loop.run_until_complete(main())

运行结果

{'code': 0, 'msg': 'login success!', 'username': 'test', 'token': '408434b72328ea6740f7f2c260a1c3f97be82fab'}

总结

如果要发送未进行表单编码的数据,可以通过传递 bytes 默认情况下内容类型设置为 'application/octet-stream':

async with session.post(url, data=b'\x00Binary-data\x00') as resp: ...

如果要发送 JSON 数据:

async with session.post(url, json={'example': 'test'}) as resp: ...

要发送具有适当内容类型的文本,只需使用data参数

async with session.post(url, data='Тест') as resp: ...


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:aiohttp 异步http请求-3.异步批量下载图片
下一篇:Spring中@Transactional(rollbackFor=Exception.class)属性用法介绍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~