前言
ClientSession是所有客户端 API 操作的核心和主要入口点。会话包含 cookie 存储和连接池,因此 cookie 和连接在同一会话发送的 HTTP 请求之间共享。
自定义请求头部
如果您需要将 HTTP 标头添加到请求中,请将它们传递给 headers 参数。如在请求头部添加"Content-Type": "application/json"
headers = {
"Content-Type": "application/json"
}
完整代码:
import aiohttp
import asyncio
async def task(session):
url = 'http://127.0.0.1:8000/api/v1/login'
headers = {
"Content-Type": "application/json"
}
body = {
"username": "test",
"password": "123456"
}
async with session.post(
url=url, json=body, headers=headers) as resp:
print(resp.status)
res = await resp.text()
print(res)
async def main():
async with aiohttp.ClientSession() as session:
await task(session)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
一般我们在传json参数的时候,会自动识别到是"Content-Type": "application/json" ,会在请求头部自动添加,所以不传也可以
await session.post(url, json={'example': 'text'})
当传data参数是dict内容的时候,会自动识为传文本类型application/x-www-form-urlencoded
await session.post(url, data={'example': 'text'})
ClientSession 会话设置默认请求头部
可以在ClientSession 会话设置默认请求头部,这样使用session发的请求都会自动带上默认的请求头部,如
headers={"Authorization": "Basic bG9naW46cGFzcw=="}
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get("http://httpbin.org/headers") as r:
json_body = await r.json()
assert json_body['headers']['Authorization'] == 'Basic bG9naW46cGFzcw=='
ClientSession 添加 Token 示例
import aiohttp
import asyncio
async def task(session):
async with session.get(url='/api/v1/userinfo') as resp:
print(resp.status)
res = await resp.text()
print(res)
async def main(token: str):
headers = {
"Authorization": f"Token {token}"
}
base_url = "http://127.0.0.1:8000"
async with aiohttp.ClientSession(
base_url=base_url, headers=headers) as session:
await task(session)
token = "a9ec55ef490efd3ef784a4ec9b546fa991996690"
loop = asyncio.get_event_loop()
loop.run_until_complete(main(token))
有些java开发的接口token格式是Authorization: Bearer {Token}
headers = {
"Authorization": f"Bearer {token}"
}
|