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 fileTake it
Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 1–12why, one step back1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters acrossremove the jar referencesKenneth Reitzbefore adoptionfad1c66
lines 13–14why, one step back13requests. It also perstists cookies across all requests made from the14Session instance.Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 15–19why, one step back1516A session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::19Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 20why, one step back20 s = requests.session()Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 21why, one step back21Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 22–23why, one step back22 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 24why, one step back24Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 25–26why, one step back25 print r.content26 # '{"cookies": {"sessioncookie": "123456789"}}'Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 27–36why, one step back272829Sessions 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 sentMerge branch 'develop'Kenneth Reitzbefore adoption3b085ed
line 37why, one step back37 c.get('http://httpbin.org/headers', headers={'x-test2': 'true'})Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 38–39why, one step back3839explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
line 40why, one step back40Any 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.Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
line 41why, one step back41explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 42–45why, one step back42.. 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.45Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption30ed664
line 46why, one step back46All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 47–48why, one step back4748big docs update on workflow of request lifecycleKenneth Reitzbefore adoption0a24de2
lines 49–69why, one step back49Body 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.69explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 70–73why, one step back7071Configuring Requests72--------------------73grocer's apostropheKenneth Reitzbefore adoption6b377cc
line 74why, one step back74Sometimes you may want to configure a request to customize its behavior. To docross-references in documentationKenneth Reitzbefore adoption5bc919a
line 75why, one step back75this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 76–80why, one step back767778Keep-Alive79----------80Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptioncf60062
line 81why, one step back81Excellent 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!explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 82–86why, one step back8283If 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'] = FalseMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 87–88why, one step back8788Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 89–91why, one step back89Asynchronous Requests90----------------------91better advanced quick startKenneth Reitzbefore adoption1708876
line 92why, one step back92Requests has first-class support for concurrent requests, poweredMerge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 93–95why, one step back93by 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 haveMerge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption30ed664
line 96why, one step back96`gevent <http://pypi.python.org/pypi/gevent>`_ this will fail::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 97–121why, one step back9798 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]>]better advanced quick startKenneth Reitzbefore adoption1708876
lines 122–127why, one step back122123.. 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)Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 128–129why, one step back128129Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 130–152why, one step back130Event 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`` requestMigrate new docs over.Kenneth Reitzbefore adoption4a7fdef
line 153why, one step back153parameter::Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 154–207why, one step back154155 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 }207Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 208–213why, one step back208209Custom Authentication210---------------------211212Requests allows you to use specify your own authentication mechanism.213Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 214–215why, one step back214Any callable which is passed as the ``auth`` argument to a request method will215have the opportunity to modify the request before it is dispatched.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 216why, one step back216Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 217–219why, one step back217Authentication implementations are subclasses of ``requests.auth.AuthBase``,218and are easy to define. Requests provides two common authentication scheme219implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 220–225why, one step back220221Let'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::225Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 226–236why, one step back226 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 rMerge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 237–239why, one step back237238Then, we can make a request using our Pizza Auth::239Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
line 240why, one step back240 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 241why, one step back241 <Response [200]>Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 242–251why, one step back242243244Verbose 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::251Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption30ed664
lines 252–253why, one step back252 >>> my_config = {'verbose': sys.stderr}253 >>> requests.get('http://httpbin.org/headers', config=my_config)Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 254–255why, one step back254 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers255 <Response [200]>