aiohttp 异步http请求-2.post 请求application/json和data
前言
aiohttp 发送post请求,body类型的常见的类型传参:
- application/json
- application/x-www-form-urlencode
application/json
POST 请求接口报文示例,Content-Type类型是application/json
POST /api/v1/login/ HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 42
Content-Type: application/json
Host: 127.0.0.1:8000
User-Agent: HTTPie/1.0.3
"password": "123456",
"username": "test"
}
于是可以使用ClientSession.post()接受 json参数
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession('http://127.0.0.1:8000') as 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())
运行结果
http://127.0.0.1:8000/api/v1/login
{"code": 0, "msg": "login success!", "username": "test", "token": "ff7b608ed22407a4cd4d2f7beb1bfe9015574bdc"}
默认情况下,会话使用 python 的标准json模块进行序列化。但可以使用不同的 serializer. ClientSession接受json_serialize 参数:
import ujson
async with aiohttp.ClientSession(
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(
aiohttp.client_exceptions.ContentTypeError: 0, 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-www-form-urlencode
POST 请求接口报文示例,Content-Type类型是application/x-www-form-urlencode
POST /api/v4/login HTTP/1.1
Content-Length: 29
Content-Type: application/x-www-form-urlencoded
username=test&password=123456
html上form表单数据的提交,只需传一个data参数即可
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession('http://127.0.0.1:8000') as session:
body = {
"password": "123456",
"username": "test"
async with session.post('/api/v4/login', data=body) as resp:
print(await resp.json())