Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

255 lines · 7.7 KiB

Last changed by

Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b

History of this file

Take it

1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also perstists cookies across all requests made from the14Session instance.1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920    s = requests.session()2122    s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23    r = s.get("http://httpbin.org/cookies")2425    print r.content26    # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::3031    headers = {'x-test': 'true'}32    auth = ('user', 'pass')3334    with requests.session(auth=auth, headers=headers) as c:3536        # both 'x-test' and 'x-test2' are sent37        c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})383940Any dictionaries that you pass to a request method will be merged with the session-level values that are set. The method-level parameters override session parameters.4142.. admonition:: Remove a Value From a Dict Parameter4344    Sometimes you'll want to omit session-level keys from a dict parameter. To do this, you simply set that key's value to ``None`` in the method-level parameter. It will automatically be omitted.4546All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.474849Body Content Workflow50----------------------5152By default, When you make a request, the body of the response isn't downloaded immediately. The response headers are downloaded when you make a request, but the content isn't downloaded until you access the :class:`Response.content` attribute.5354Let's walk through it::5556    tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'57    r = requests.get(tarball_url)5859The request has been made, but the connection is still open. The response body has not been downloaded yet. ::6061    r.content6263The content has been downloaded and cached.6465You can override this default behavior with the ``prefetch`` parameter::6667    r = requests.get(tarball_url, prefetch=True)68    # Blocks until all of request body has been downloaded.697071Configuring Requests72--------------------7374Sometimes you may want to configure a request to customize its behavior. To do75this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.767778Keep-Alive79----------8081Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!8283If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::8485    s = requests.session()86    s.config['keep_alive'] = False878889Asynchronous Requests90----------------------9192Requests has first-class support for concurrent requests, powered93by gevent. This allows you to send a bunch of HTTP requests at the same9495First, let's import the async module. Heads up — if you don't have96`gevent <http://pypi.python.org/pypi/gevent>`_ this will fail::9798    from requests import async99100The ``async`` module has the exact same api as ``requests``, except it101doesn't send the request immediately. Instead, it returns the ``Request``102object.103104We can build a list of ``Request`` objects easily::105106    urls = [107        'http://python-requests.org',108        'http://httpbin.org',109        'http://python-guide.org',110        'http://kennethreitz.com'111    ]112113    rs = [async.get(u) for u in urls]114115Now we have a list of ``Request`` objects, ready to be sent. We could send them116one at a time with ``Request.send()``, but that would take a while.  Instead,117we'll send them all at the same time with ``async.map()``.  Using ``async.map()``118will also guarantee execution of the ``response`` hook, described below. ::119120    >>> async.map(rs)121    [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]122123.. admonition:: Throttling124125    The ``map`` function also takes a ``size`` parameter, that specifies the nubmer of connections to make at a time::126127        async.map(rs, size=5)128129130Event Hooks131-----------132133Requests has a hook system that you can use to manipulate portions of134the request process, or signal event handling.135136Available hooks:137138``args``:139    A dictionary of the arguments being sent to Request().140141``pre_request``:142    The Request object, directly before being sent.143144``post_request``:145    The Request object, directly after being sent.146147``response``:148    The response generated from a Request.149150151You can assign a hook function on a per-request basis by passing a152``{hook_name: callback_function}`` dictionary to the ``hooks`` request153parameter::154155    hooks=dict(args=print_url)156157That ``callback_function`` will receive a chunk of data as its first158argument.159160::161162    def print_url(args):163        print args['url']164165If an error occurs while executing your callback, a warning is given.166167If the callback function returns a value, it is assumed that it is to168replace the data that was passed in. If the function doesn't return169anything, nothing else is effected.170171Let's print some request method arguments at runtime::172173    >>> requests.get('http://httpbin', hooks=dict(args=print_url))174    http://httpbin175    <Response [200]>176177Let's hijack some arguments this time with a new callback::178179    def hack_headers(args):180        if not args[headers]:181            args['headers'] = dict()182183        args['headers'].update({'X-Testing': 'True'})184185        return args186187    hooks = dict(args=hack_headers)188    headers = dict(yo=dawg)189190And give it a try::191192    >>> requests.get('http://httpbin/headers', hooks=hooks, headers=headers)193    {194        "headers": {195            "Content-Length": "",196            "Accept-Encoding": "gzip",197            "Yo": "dawg",198            "X-Forwarded-For": "::ffff:24.127.96.129",199            "Connection": "close",200            "User-Agent": "python-requests.org",201            "Host": "httpbin.org",202            "X-Testing": "True",203            "X-Forwarded-Protocol": "",204            "Content-Type": ""205        }206    }207208209Custom Authentication210---------------------211212Requests allows you to use specify your own authentication mechanism.213214Any callable which is passed as the ``auth`` argument to a request method will215have the opportunity to modify the request before it is dispatched.216217Authentication implementations are subclasses of ``requests.auth.AuthBase``,218and are easy to define. Requests provides two common authentication scheme219implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.220221Let's pretend that we have a web service that will only respond if the222``X-Pizza`` header is set to a password value. Unlikely, but just go with it.223224::225226    from requests.auth import AuthBase227    class PizzaAuth(AuthBase):228        """Attaches HTTP Pizza Authentication to the given Request object."""229        def __init__(self, username):230            # setup any auth-related data here231            self.username = username232        233        def __call__(self, r):234            # modify and return the request235            r.headers['X-Pizza'] = self.username236            return r237238Then, we can make a request using our Pizza Auth::239240    >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))241    <Response [200]>242243244Verbose Logging245---------------246247If you want to get a good look at what HTTP requests are being sent248by your application, you can turn on verbose logging.249250To do so, just configure Requests with a stream to write to::251252    >>> my_config = {'verbose': sys.stderr}253    >>> requests.get('http://httpbin.org/headers', config=my_config)254    2011-08-17T03:04:23.380175   GET   http://httpbin.org/headers255    <Response [200]>