1. pip install aiohttp

客户端

快速开始

  1. import aiohttp
  2. import asyncio
  3. async def main():
  4. # 创建客户端会话
  5. async with aiohttp.ClientSession() as session:
  6. # 发起get请求
  7. async with session.get('https://baidu.com') as response:
  8. # 返回状态码
  9. print("Status", response.status)
  10. # 返回内容格式
  11. print("Content-type",response.headers["content-type"])
  12. # 对text格式进行解析
  13. html = await response.text()
  14. print(html[:16])
  15. # 获取JSON数据
  16. async with session.get(url) as response:
  17. print(response.json())
  18. # 发起带有JSON数据的post请求
  19. async with session.post(url,json={"key":"value"}) as response:
  20. # 发送form-encoded格式数据 {"form":{"key":"value"}}
  21. async with session.post(url,data={"key":"value"}) as response:
  22. # 发送multipart-encoded格式数据
  23. files = {"file",open("data.xls","rb"),filename="report.xls"}
  24. await session.post(url,data=files)
  25. # 创建异步事件循环。
  26. loop = asyncio.get_event_loop()
  27. loop.run_until_complete(main())