Skip to content
Myr

requests.async. Oh, yes :)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 30d937f · Browse files · 1 file+75 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+75 added−0 removed

  • other:+75 added−0 removed

1 file+75 added−0 removed

added:requests/async.py+75 added
1# -*- coding: utf-8 -*-23"""4reqeusts.async5~~~~~~~~~~~~~~67This module contains an asyncronous replica of ``requests.api``, powered8by gevent. All API methods return a ``Request`` instance (as opposed to9``Response``). A list of requests can be sent with ``map()``.10"""1112try:13 import gevent14 from gevent import monkey as curious_george15except ImportError:16 raise RuntimeError('Gevent is required for requests.async.')1718# Monkey-patch.19curious_george.patch_all(thread=False)2021from . import api22from .hooks import dispatch_hook23from .packages.urllib3.poolmanager import PoolManager242526def _patched(f):27 """Patches a given api function to not send."""2829 def wrapped(*args, **kwargs):30 return f(*args, _return_request=True, **kwargs)3132 return wrapped333435def _send(r, pools=None):36 """Dispatcher."""3738 if pools:39 r._pools = pools4041 r.send()4243 # Post-request hook.44 r = dispatch_hook('post_request', r.hooks, r)4546 # Response manipulation hook.47 r.response = dispatch_hook('response', r.hooks, r.response)4849 return r.response5051# Patched requests.api functions.52get = _patched(api.get)53head = _patched(api.head)54post = _patched(api.post)55put = _patched(api.put)56patch = _patched(api.patch)57delete = _patched(api.delete)58request = _patched(api.request)5960from requests.sessions import session6162def map(requests, keep_alive=False):63 """Sends the requests... Asynchronously."""6465 if keep_alive:66 pools = PoolManager(num_pools=len(requests), maxsize=1)67 else:68 pools = None6970 jobs = [gevent.spawn(_send, r, pools=pools) for r in requests]71 gevent.joinall(jobs)7273 return [r.response for r in requests]7475