aiohttp
内部已集成了aiohttp库,可以直接使用。目前只支持HTTP client功能。参考 aiohttp。
示例
1import json
2import asyncio
3import aiohttp
4
5
6async def get():
7 async with aiohttp.ClientSession() as session:
8 async with session.get("https://httpbin.org/get") as resp:
9 print("status:", resp.status)
10 print("headers:", resp.headers)
11 body = await resp.text()
12 print("body:", body)
13
14
15async def post():
16 async with aiohttp.ClientSession() as session:
17 url = "https://httpbin.org/post"
18 headers = {"Content-Type": "application/json"}
19 payload = {"name": "micropython", "version": "1.24.1"}
20 async with session.post(
21 url=url, data=json.dumps(payload), headers=headers
22 ) as resp:
23 print("status:", resp.status)
24 print("headers:", resp.headers)
25 body = await resp.json()
26 print("body:", body)
27
28
29async def post_http11():
30 async with aiohttp.ClientSession(version=aiohttp.HttpVersion11) as session:
31 url = "https://httpbin.org/post"
32 headers = {
33 "Content-Type": "application/json",
34 "Accept-Encoding": "identity",
35 "Connection": "close",
36 "TE": "identity",
37 }
38 payload = {"name": "micropython", "version": "1.24.1"}
39 async with session.post(
40 url=url, data=json.dumps(payload), headers=headers
41 ) as resp:
42 print("status:", resp.status)
43 print("headers:", resp.headers)
44 body = await resp.json()
45 print("body:", body)
46
47
48async def main():
49 print("start aiohttp")
50 await get()
51 print("get ok")
52 await post()
53 print("post ok")
54 await post_http11()
55 print("post http11 ok")
56 print("aiohttp done")
57
58
59asyncio.run(main())