-
Notifications
You must be signed in to change notification settings - Fork 1
/
aiohttp_client.py
78 lines (52 loc) · 1.73 KB
/
aiohttp_client.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import aiohttp
import asyncio
import lru
import os
import yarl
# max # of requests per session
_max_number_sessions = int(os.environ.get("AIOHTTP_SESSION_SIZE", "200"))
def session_purged(key, value):
asyncio.ensure_future(value.close())
_sessions = lru.LRU(_max_number_sessions, callback=session_purged)
_counts = {}
_connect_options = {
"ttl_dns_cache": int(os.environ.get("AIOHTTP_SESSION_DNS_CACHE", "20")),
"limit": int(os.environ.get("AIOHTTP_SESSION_LIMIT", "500")),
"force_close": True,
"enable_cleanup_closed": True,
}
def get_session(url):
url = yarl.URL(url)
if url.host not in _sessions:
_sessions[url.host] = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(**_connect_options)
)
_counts[url.host] = 0
_counts[url.host] += 1
return _sessions[url.host]
async def close():
for session in _sessions.values():
await session.close()
_sessions.clear()
_counts.clear()
def post(url, *args, **kwargs):
session = get_session(url)
return session.post(url, *args, **kwargs)
def get(url, *args, **kwargs):
session = get_session(url)
return session.get(url, *args, **kwargs)
def patch(url, *args, **kwargs):
session = get_session(url)
return session.patch(url, *args, **kwargs)
def delete(url, *args, **kwargs):
session = get_session(url)
return session.delete(url, *args, **kwargs)
def head(url, *args, **kwargs):
session = get_session(url)
return session.head(url, *args, **kwargs)
def put(url, *args, **kwargs):
session = get_session(url)
return session.put(url, *args, **kwargs)
def options(url, *args, **kwargs):
session = get_session(url)
return session.options(url, *args, **kwargs)