Skip to content
Myr

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

6 files+119 added−30 removed

modified:docs/user/advanced.rst+34 added
41 unmodified lines
42 Certain parameters are best set at the ``request.config`` level43 (e.g.. a global proxy, user agent header).444546Asynchronous Requests47----------------------4849Requests has first-class support for non-blocking i/o requests, powered50by gevent. This allows you to send a bunch of HTTP requests at the same5152First, let's import the async module. Heads up — if you don't have53**gevent** installed, this will fail.::5455 from requests import async5657The ``async`` module has the exact same api as ``requests``, except it58doesn't send the request immediately. Instead, it returns the ``Request``59object.6061We can build a list of ``Request`` objects easily::6263 urls = [64 'http://python-requests.org',65 'http://httpbin.org',66 'http://python-guide.org',67 'http://kennethreitz.com'68 ]6970 rs = [async.get(u) for u in urls]7172Now we have a list of ``Request`` objects, ready to be sent. We could73send them one at a time with ``Request.send()``, but that would take a while.74Instead, we'll send them all at the same time with ``async.map()``::7576 >>> async.map(rs)77 [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]787980Event Hooks81-----------8283Requests has a hook system that you can use to manipulate portions of
88 unmodified lines
modified:requests/api.py+6 added-2 removed
15 unmodified lines
16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict1920from urlparse import urlparse2021__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')2223def 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):2627 """Constructs and sends a :class:`Request <models.Request>`.28 Returns :class:`Response <models.Response>` object.29
23 unmodified lines
53 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 lines
6768 # Pre-request hook.69 r = dispatch_hook('pre_request', hooks, r)7071 # Don't send if asked nicely.72 if not return_response:73 return r7475 # Send the HTTP Request.76 r.send()7778 # Post-request hook.
114 unmodified lines
modified:requests/async.py+68 added-25 removed
1# -*- coding: utf-8 -*-23"""4 requests.async5 ~~~~~~~~~~~~~~4requests.async5~~~~~~~~~~~~~~67 This module implements the main Requests system, after monkey-patching8 the urllib2 module with eventlet or gevent..910 :copyright: (c) 2011 by Kenneth Reitz.11 :license: ISC, see LICENSE for more details.7This module contains an asynchronous 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.')1715from __future__ import absolute_import18# Monkey-patch.19curious_george.patch_all(thread=False)2017import urllib18import urllib221from . import api22from .hooks import dispatch_hook2320from urllib2 import HTTPError2425__all__ = (26 'map',27 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'28)2923try:24 import eventlet25 eventlet.monkey_patch()26except ImportError:27 pass3029if not 'eventlet' in locals():30 try:31 from gevent import monkey32 monkey.patch_all()33 except ImportError:34 pass31def _patched(f):32 """Patches a given API function to not send."""3334 def wrapped(*args, **kwargs):35 return f(*args, return_response=False, **kwargs)3637if not 'eventlet' in locals():38 raise ImportError('No Async adaptations of urllib2 found!')37 return wrapped383941from .core import *40def _send(r, pools=None):41 """Sends a given Request object."""4243 if pools:44 r._pools = pools4546 r.send()4748 # Post-request hook.49 r = dispatch_hook('post_request', r.hooks, r)5051 # Response manipulation hook.52 r.response = dispatch_hook('response', r.hooks, r.response)5354 return r.response555657# Patched requests.api functions.58get = _patched(api.get)59head = _patched(api.head)60post = _patched(api.post)61put = _patched(api.put)62patch = _patched(api.patch)63delete = _patched(api.delete)64request = _patched(api.request)656667def map(requests, prefetch=True):68 """Concurrently converts a list of Requests to Responses.6970 :param requests: a collection of Request objects.71 :param prefetch: If False, the content will not be downloaded immediately.72 """7374 jobs = [gevent.spawn(_send, r) for r in requests]75 gevent.joinall(jobs)7677 if prefetch:78 [r.response.content for r in requests]7980 return [r.response for r in requests]81828384
modified:requests/core.py+2 added-2 removed
10 unmodified lines
1112"""1314__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 lines
modified:requests/models.py+3 added-1 removed
35 unmodified lines
3637 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):4142 #: Float describ the timeout of the request.43 # (Use socket.setdefaulttimeout() as fallback)44 self.timeout = timeout
48 unmodified lines
9394 #: True if Request has been sent.95 self.sent = False9697 #: Event-handling hooks.98 self.hooks = hooks99100 # Header manipulation and defaults.101102 if settings.accept_gzip:
523 unmodified lines
modified:HISTORY.rst+6 added
1History2-------340.6.3 (??)5+++++++++++67* Beautiful ``requests.async`` module, for making async requests w/ gevent.89100.6.2 (2011-10-09)11++++++++++++++++++1213* ``allow_redirects=False`` on safe verbs
159 unmodified lines