Merge pull request #201 from kennethreitz/feature/async
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Beautiful Async Module
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 597f0ae, a4b87c6 · Browse files · 6 files·+119 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+119 added−30 removed
- other:+119 added−30 removed
Provenance
- Commit
e9b4def- Tree
e9f74ab- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
597f0ae- Parent 2
a4b87c6
6 files changed+119 added−30 removed
modified:docs/user/advanced.rst+34 added
41 unmodified lines42 Certain parameters are best set at the ``request.config`` level43 (e.g.. a global proxy, user agent header).44 45 46+Asynchronous Requests47+----------------------48+49+Requests has first-class support for non-blocking i/o requests, powered50+by gevent. This allows you to send a bunch of HTTP requests at the same51+52+First, let's import the async module. Heads up — if you don't have53+**gevent** installed, this will fail.::54+55+ from requests import async56+57+The ``async`` module has the exact same api as ``requests``, except it58+doesn't send the request immediately. Instead, it returns the ``Request``59+object.60+61+We can build a list of ``Request`` objects easily::62+63+ urls = [64+ 'http://python-requests.org',65+ 'http://httpbin.org',66+ 'http://python-guide.org',67+ 'http://kennethreitz.com'68+ ]69+70+ rs = [async.get(u) for u in urls]71+72+Now we have a list of ``Request`` objects, ready to be sent. We could73+send them one at a time with ``Request.send()``, but that would take a while.74+Instead, we'll send them all at the same time with ``async.map()``::75+76+ >>> async.map(rs)77+ [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]78+79+80 Event Hooks81 -----------82 83 Requests has a hook system that you can use to manipulate portions of88 unmodified linesmodified:requests/api.py+6 added-2 removed
15 unmodified lines16 from .status_codes import codes17 from .hooks import dispatch_hook18 from .utils import cookiejar_from_dict19 20-from urlparse import urlparse20 21 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')22 23 def request(method, url,24 params=None, data=None, headers=None, cookies=None, files=None, auth=None,26- timeout=None, allow_redirects=False, proxies=None, hooks=None):25+ timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):26 27 """Constructs and sends a :class:`Request <models.Request>`.28 Returns :class:`Response <models.Response>` object.29 23 unmodified lines53 headers = headers,54 cookiejar = cookies,55 files = files,56 auth = auth,57+ hooks = hooks,58 timeout = timeout or config.settings.timeout,59 allow_redirects = allow_redirects,60 proxies = proxies or config.settings.proxies,61 )5 unmodified lines67 68 # Pre-request hook.69 r = dispatch_hook('pre_request', hooks, r)70 71+ # Don't send if asked nicely.72+ if not return_response:73+ return r74+75 # Send the HTTP Request.76 r.send()77 78 # Post-request hook.114 unmodified linesmodified:requests/async.py+68 added-25 removed
1 # -*- coding: utf-8 -*-2 3 """4- requests.async5- ~~~~~~~~~~~~~~4+requests.async5+~~~~~~~~~~~~~~6 7- This module implements the main Requests system, after monkey-patching8- the urllib2 module with eventlet or gevent..9-10- :copyright: (c) 2011 by Kenneth Reitz.11- :license: ISC, see LICENSE for more details.7+This module contains an asynchronous replica of ``requests.api``, powered8+by gevent. All API methods return a ``Request`` instance (as opposed to9+``Response``). A list of requests can be sent with ``map()``.10 """11 12+try:13+ import gevent14+ from gevent import monkey as curious_george15+except ImportError:16+ raise RuntimeError('Gevent is required for requests.async.')17 15-from __future__ import absolute_import18+# Monkey-patch.19+curious_george.patch_all(thread=False)20 17-import urllib18-import urllib221+from . import api22+from .hooks import dispatch_hook23 20-from urllib2 import HTTPError24 25+__all__ = (26+ 'map',27+ 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28+)29 23-try:24- import eventlet25- eventlet.monkey_patch()26-except ImportError:27- pass30 29-if not 'eventlet' in locals():30- try:31- from gevent import monkey32- monkey.patch_all()33- except ImportError:34- pass31+def _patched(f):32+ """Patches a given API function to not send."""33 34+ def wrapped(*args, **kwargs):35+ return f(*args, return_response=False, **kwargs)36 37-if not 'eventlet' in locals():38- raise ImportError('No Async adaptations of urllib2 found!')37+ return wrapped38 39 41-from .core import *40+def _send(r, pools=None):41+ """Sends a given Request object."""42+43+ if pools:44+ r._pools = pools45+46+ r.send()47+48+ # Post-request hook.49+ r = dispatch_hook('post_request', r.hooks, r)50+51+ # Response manipulation hook.52+ r.response = dispatch_hook('response', r.hooks, r.response)53+54+ return r.response55+56+57+# Patched requests.api functions.58+get = _patched(api.get)59+head = _patched(api.head)60+post = _patched(api.post)61+put = _patched(api.put)62+patch = _patched(api.patch)63+delete = _patched(api.delete)64+request = _patched(api.request)65+66+67+def map(requests, prefetch=True):68+ """Concurrently converts a list of Requests to Responses.69+70+ :param requests: a collection of Request objects.71+ :param prefetch: If False, the content will not be downloaded immediately.72+ """73+74+ jobs = [gevent.spawn(_send, r) for r in requests]75+ gevent.joinall(jobs)76+77+ if prefetch:78+ [r.response.content for r in requests]79+80+ return [r.response for r in requests]81+82+83+84+modified:requests/core.py+2 added-2 removed
10 unmodified lines11 12 """13 14 __title__ = 'requests'15-__version__ = '0.6.1'16-__build__ = 0x00060115+__version__ = '0.6.3'16+__build__ = 0x00060317 __author__ = 'Kenneth Reitz'18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 7 unmodified linesmodified:requests/models.py+3 added-1 removed
35 unmodified lines36 37 def __init__(self,38 url=None, headers=dict(), files=None, method=None, data=dict(),39 params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,40- allow_redirects=False, proxies=None):40+ allow_redirects=False, proxies=None, hooks=None):41 42 #: Float describ the timeout of the request.43 # (Use socket.setdefaulttimeout() as fallback)44 self.timeout = timeout48 unmodified lines93 94 #: True if Request has been sent.95 self.sent = False96 97+ #: Event-handling hooks.98+ self.hooks = hooks99 100 # Header manipulation and defaults.101 102 if settings.accept_gzip:523 unmodified linesmodified:HISTORY.rst+6 added
1 History2 -------3 4+0.6.3 (??)5++++++++++++6+7+* Beautiful ``requests.async`` module, for making async requests w/ gevent.8+9+10 0.6.2 (2011-10-09)11 ++++++++++++++++++12 13 * ``allow_redirects=False`` on safe verbs159 unmodified lines