Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

257 lines · 7.9 KiB

Last changed by

Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf

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 persists 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!8283Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``prefetch`` to ``True`` or read the ``content`` property of the ``Response`` object.8485If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::8687    s = requests.session()88    s.config['keep_alive'] = False899091Asynchronous Requests92----------------------9394Requests has first-class support for concurrent requests, powered by gevent.95This allows you to send a bunch of HTTP requests at the same time.9697First, let's import the async module. Heads up — if you don't have98`gevent <http://pypi.python.org/pypi/gevent>`_ this will fail::99100    from requests import async101102The ``async`` module has the exact same api as ``requests``, except it103doesn't send the request immediately. Instead, it returns the ``Request``104object.105106We can build a list of ``Request`` objects easily::107108    urls = [109        'http://python-requests.org',110        'http://httpbin.org',111        'http://python-guide.org',112        'http://kennethreitz.com'113    ]114115    rs = [async.get(u) for u in urls]116117Now we have a list of ``Request`` objects, ready to be sent. We could send them118one at a time with ``Request.send()``, but that would take a while.  Instead,119we'll send them all at the same time with ``async.map()``.  Using ``async.map()``120will also guarantee execution of the ``response`` hook, described below. ::121122    >>> async.map(rs)123    [<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]124125.. admonition:: Throttling126127    The ``map`` function also takes a ``size`` parameter, that specifies the number of connections to make at a time::128129        async.map(rs, size=5)130131132Event Hooks133-----------134135Requests has a hook system that you can use to manipulate portions of136the request process, or signal event handling.137138Available hooks:139140``args``:141    A dictionary of the arguments being sent to Request().142143``pre_request``:144    The Request object, directly before being sent.145146``post_request``:147    The Request object, directly after being sent.148149``response``:150    The response generated from a Request.151152153You can assign a hook function on a per-request basis by passing a154``{hook_name: callback_function}`` dictionary to the ``hooks`` request155parameter::156157    hooks=dict(args=print_url)158159That ``callback_function`` will receive a chunk of data as its first160argument.161162::163164    def print_url(args):165        print args['url']166167If an error occurs while executing your callback, a warning is given.168169If the callback function returns a value, it is assumed that it is to170replace the data that was passed in. If the function doesn't return171anything, nothing else is effected.172173Let's print some request method arguments at runtime::174175    >>> requests.get('http://httpbin', hooks=dict(args=print_url))176    http://httpbin177    <Response [200]>178179Let's hijack some arguments this time with a new callback::180181    def hack_headers(args):182        if not args[headers]:183            args['headers'] = dict()184185        args['headers'].update({'X-Testing': 'True'})186187        return args188189    hooks = dict(args=hack_headers)190    headers = dict(yo=dawg)191192And give it a try::193194    >>> requests.get('http://httpbin/headers', hooks=hooks, headers=headers)195    {196        "headers": {197            "Content-Length": "",198            "Accept-Encoding": "gzip",199            "Yo": "dawg",200            "X-Forwarded-For": "::ffff:24.127.96.129",201            "Connection": "close",202            "User-Agent": "python-requests.org",203            "Host": "httpbin.org",204            "X-Testing": "True",205            "X-Forwarded-Protocol": "",206            "Content-Type": ""207        }208    }209210211Custom Authentication212---------------------213214Requests allows you to use specify your own authentication mechanism.215216Any callable which is passed as the ``auth`` argument to a request method will217have the opportunity to modify the request before it is dispatched.218219Authentication implementations are subclasses of ``requests.auth.AuthBase``,220and are easy to define. Requests provides two common authentication scheme221implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.222223Let's pretend that we have a web service that will only respond if the224``X-Pizza`` header is set to a password value. Unlikely, but just go with it.225226::227228    from requests.auth import AuthBase229    class PizzaAuth(AuthBase):230        """Attaches HTTP Pizza Authentication to the given Request object."""231        def __init__(self, username):232            # setup any auth-related data here233            self.username = username234235        def __call__(self, r):236            # modify and return the request237            r.headers['X-Pizza'] = self.username238            return r239240Then, we can make a request using our Pizza Auth::241242    >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))243    <Response [200]>244245246Verbose Logging247---------------248249If you want to get a good look at what HTTP requests are being sent250by your application, you can turn on verbose logging.251252To do so, just configure Requests with a stream to write to::253254    >>> my_config = {'verbose': sys.stderr}255    >>> requests.get('http://httpbin.org/headers', config=my_config)256    2011-08-17T03:04:23.380175   GET   http://httpbin.org/headers257    <Response [200]>