客户端
发起请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | import asyncio
import aiohttp
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
"""
200
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "Python/3.7 aiohttp/3.5.4"
},
"origin": "36.102.18.170, 36.102.18.170",
"url": "https://httpbin.org/get"
}
"""
|
会话(session)对象,由 ClientSession 对象赋值而来,还有一个变量 response,它其实是 ClientResponse 对象。我们可以从这个响应对象中获取我们任何想要的信息。
协程方法 ClientSession.get() 的主要参数接收一个 HTTP URL
发起 HTTP POST 请求我们可以使用协程方法 ClientSession.post()
| session.post('http://httpbin.org/post', data=b'data')
|
其他的 HTTP 方法也同样支持
| session.put('http://httpbin.org/put', data=b'data')
session.delete('http://httpbin.org/delete')
session.head('http://httpbin.org/get')
session.options('http://httpbin.org/get')
session.patch('http://httpbin.org/patch', data=b'data')
|
注意:不要为每个请求都创建一个会话。大多数情况下每个应用程序只需要一个会话就可以执行所有的请求。每个会话对象都包含一个连接池,可复用的连接和持久连接状态(keep-alives,这两个是默认的)可提升总体的执行效率
使用SSL请求
1
2
3
4
5
6
7
8
9
10
11
12
13 | import ssl
import aiohttp
import asyncio
sslcontext = ssl.create_default_context(cafile='xxxca.pem') # 根CA证书
sslcontext.load_cert_chain('xxx.crt.pem',
'xxx.key.pem') # 客户端证书
async def test():
async with aiohttp.ClientSession() as session:
async with session.get("https://xxx.com:8443", ssl=sslcontext) as r:
html = await r.text()
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
|
WebSocket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 | import asyncio
import aiohttp
from datetime import datetime
async def main():
async with aiohttp.ClientSession() as session:
# async with session.ws_connect('ws://hq.sinajs.cn/wskt?list=s_sh000001',
# heartbeat=1) as ws:
# async with session.ws_connect('ws://127.0.0.1:8080',
# heartbeat=1) as ws:
async with session.ws_connect('ws://127.0.0.1:3012') as ws:
# async with session.ws_connect('ws://127.0.0.1:8080') as ws:
try:
await ws.send_str("hhh")
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg.data)
elif msg.type == aiohttp.WSMsgType.CLOSED:
print("ws close.")
break
elif msg.type == aiohttp.WSMsgType.ERROR:
print("error!")
break
except Exception as e:
print(f"ERROR: {type(e)}:{e}")
raise e
start_time = datetime.now()
print(start_time)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
now_time = datetime.now()
print(now_time)
print('run time = ', now_time - start_time)
|