-
Notifications
You must be signed in to change notification settings - Fork 27
/
requests_threads.py
72 lines (57 loc) · 2.2 KB
/
requests_threads.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
import inspect
from twisted.internet import threads
from twisted.internet.defer import ensureDeferred
from twisted.internet.error import ReactorAlreadyInstalledError
from twisted.internet import task
from requests import Session
class AsyncSession(Session):
"""An asynchronous Requests session.
Provides cookie persistence, connection-pooling, and configuration.
Basic Usage::
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
<Response [200]>
Or as a context manager::
>>> with requests.Session() as s:
>>> s.get('http://httpbin.org/get')
<Response [200]>
"""
def __init__(self, n=None, reactor=None, loop=None, *args, **kwargs):
if reactor is None:
try:
import asyncio
loop = loop or asyncio.get_event_loop()
try:
from twisted.internet import asyncioreactor
asyncioreactor.install(loop)
except (ReactorAlreadyInstalledError, ImportError):
pass
except ImportError:
pass
# Adjust the pool size, according to n.
if n:
from twisted.internet import reactor
pool = reactor.getThreadPool()
pool.adjustPoolsize(0, n)
super(AsyncSession, self).__init__(*args, **kwargs)
def request(self, *args, **kwargs):
"""Maintains the existing api for Session.request.
Used by all of the higher level methods, e.g. Session.get.
"""
func = super(AsyncSession, self).request
return threads.deferToThread(func, *args, **kwargs)
def wrap(self, *args, **kwargs):
return ensureDeferred(*args, **kwargs)
def run(self, f):
# Python 3 only.
if hasattr(inspect, 'iscoroutinefunction'):
# Is this a coroutine?
if inspect.iscoroutinefunction(f):
def w(reactor):
return self.wrap(f())
# If so, convert coroutine to Deferred automatically.
return task.react(w)
else:
# Otherwise, run the Deferred.
return task.react(f)