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 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 acrossMerge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
line 13why, one step back13requests. It also persists cookies across all requests made from theremove the jar referencesKenneth Reitzbefore adoptionfad1c66
line 14why, one step back14Session 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–51why, one step back49Body Content Workflow50----------------------51Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
line 52why, one step back52By 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.big docs update on workflow of request lifecycleKenneth Reitzbefore adoption0a24de2
lines 53–69why, one step back5354Let'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
line 82why, one step back82Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption961f78a
lines 83–84why, one step back83Note 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.84explain sessions and keep aliveKenneth Reitzbefore adoption4e8b680
lines 85–88why, one step back85If 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'] = FalseMerge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 89–90why, one step back8990Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 91–93why, one step back91Asynchronous Requests92----------------------93Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
lines 94–95why, one step back94Requests has first-class support for concurrent requests, powered by gevent.95This allows you to send a bunch of HTTP requests at the same time.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 96–97why, one step back9697First, let's import the async module. Heads up — if you don't haveMerge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption30ed664
line 98why, one step back98`gevent <http://pypi.python.org/pypi/gevent>`_ this will fail::Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 99–123why, one step back99100 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]>]better advanced quick startKenneth Reitzbefore adoption1708876
lines 124–126why, one step back124125.. admonition:: Throttling126Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption961f78a
line 127why, one step back127 The ``map`` function also takes a ``size`` parameter, that specifies the number of connections to make at a time::better advanced quick startKenneth Reitzbefore adoption1708876
lines 128–129why, one step back128129 async.map(rs, size=5)Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 130–131why, one step back130131Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 132–154why, one step back132Event 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`` requestMigrate new docs over.Kenneth Reitzbefore adoption4a7fdef
line 155why, one step back155parameter::Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 156–209why, one step back156157 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 }209Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 210–215why, one step back210211Custom Authentication212---------------------213214Requests allows you to use specify your own authentication mechanism.215Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 216–217why, one step back216Any callable which is passed as the ``auth`` argument to a request method will217have the opportunity to modify the request before it is dispatched.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 218why, one step back218Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 219–221why, one step back219Authentication implementations are subclasses of ``requests.auth.AuthBase``,220and are easy to define. Requests provides two common authentication scheme221implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 222–227why, one step back222223Let'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::227Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 228–233why, one step back228 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 = usernameMerge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionfad9abf
line 234why, one step back234Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
lines 235–238why, one step back235 def __call__(self, r):236 # modify and return the request237 r.headers['X-Pizza'] = self.username238 return rMerge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
lines 239–241why, one step back239240Then, we can make a request using our Pizza Auth::241Merge branch 'auth_callables' of https://github.com/idangazit/requests into developKenneth Reitzbefore adoptiona7a619b
line 242why, one step back242 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))Merge branch 'develop' into feature/rewriteKenneth Reitzbefore adoption95336a0
line 243why, one step back243 <Response [200]>Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 244–253why, one step back244245246Verbose 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::253Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoption30ed664
lines 254–255why, one step back254 >>> my_config = {'verbose': sys.stderr}255 >>> requests.get('http://httpbin.org/headers', config=my_config)Merge branch 'develop'Kenneth Reitzbefore adoption81d5997
lines 256–257why, one step back256 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers257 <Response [200]>