advanced.rst
This file
Path
docs/user/advanced.rst
798 lines · 27.7 KiB
Last changed by
Merge pull request #2374 from krvc/fix_linkIan Cordascobefore adoptione23bf10
History of this fileTake it
The walk stopped after 200 commits: lines older than 592fb34 point at it.
try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 1–7why, one step back1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.7Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 8why, one step back8.. _session-objects:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 9–40why, one step back910Session Objects11---------------1213The Session object allows you to persist certain parameters across14requests. It also persists cookies across all requests made from the15Session instance.1617A Session object has all the methods of the main Requests API.1819Let's persist some cookies across requests::2021 s = requests.Session()2223 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')24 r = s.get("http://httpbin.org/cookies")2526 print(r.text)27 # '{"cookies": {"sessioncookie": "123456789"}}'282930Sessions can also be used to provide default data to the request methods. This31is done by providing data to the properties on a Session object::3233 s = requests.Session()34 s.auth = ('user', 'pass')35 s.headers.update({'x-test': 'true'})3637 # both 'x-test' and 'x-test2' are sent38 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})3940Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 41–43why, one step back41Any dictionaries that you pass to a request method will be merged with the42session-level values that are set. The method-level parameters override session43parameters.try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 44–46why, one step back4445.. admonition:: Remove a Value From a Dict Parameter46Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 47–49why, one step back47 Sometimes you'll want to omit session-level keys from a dict parameter. To48 do this, you simply set that key's value to ``None`` in the method-level49 parameter. It will automatically be omitted.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 50why, one step back50Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 51–52why, one step back51All values that are contained within a session are directly available to you.52See the :ref:`Session API Docs <sessionapi>` to learn more.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 53why, one step back53Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
lines 54–55why, one step back54.. _request-and-response-objects:55try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 56–87why, one step back56Request and Response Objects57----------------------------5859Whenever a call is made to ``requests.get()`` and friends you are doing two60major things. First, you are constructing a ``Request`` object which will be61sent off to a server to request or query some resource. Second, a ``Response``62object is generated once ``requests`` gets a response back from the server.63The Response object contains all of the information returned by the server and64also contains the ``Request`` object you created originally. Here is a simple65request to get some very important information from Wikipedia's servers::6667 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')6869If we want to access the headers the server sent back to us, we do this::7071 >>> r.headers72 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':73 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':74 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',75 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',76 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,77 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':78 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,79 MISS from cp1010.eqiad.wmnet:80'}8081However, if we want to get the headers we sent the server, we simply access the82request, and then the request's headers::8384 >>> r.request.headers85 {'Accept-Encoding': 'identity, deflate, compress, gzip',86 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}87Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
lines 88–89why, one step back88.. _prepared-requests:89try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 90–92why, one step back90Prepared Requests91-----------------92Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 93why, one step back93Whenever you receive a :class:`Response <requests.Response>` objecttry gumroad overlayKenneth Reitzbefore adoption592fb34
lines 94–101why, one step back94from an API call or a Session call, the ``request`` attribute is actually the95``PreparedRequest`` that was used. In some cases you may wish to do some extra96work to the body or headers (or anything else really) before sending a97request. The simple recipe for this is the following::9899 from requests import Request, Session100101 s = Session()fix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b
lines 102–107why, one step back102 req = Request('GET', url,103 data=data,104 headers=header105 )106 prepped = req.prepare()107try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 108–109why, one step back108 # do something with prepped.body109 # do something with prepped.headersfix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b
line 110why, one step back110try gumroad overlayKenneth Reitzbefore adoption592fb34
line 111why, one step back111 resp = s.send(prepped,fix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b
lines 112–118why, one step back112 stream=stream,113 verify=verify,114 proxies=proxies,115 cert=cert,116 timeout=timeout117 )118try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 119–121why, one step back119 print(resp.status_code)120121Since you are not doing anything special with the ``Request`` object, youMerge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
line 122why, one step back122prepare it immediately and modify the ``PreparedRequest`` object. You thentry gumroad overlayKenneth Reitzbefore adoption592fb34
line 123why, one step back123send that with the other parameters you would have sent to ``requests.*`` orMerge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40
line 124why, one step back124``Session.*``.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 125why, one step back125Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 126–129why, one step back126However, the above code will lose some of the advantages of having a Requests127:class:`Session <requests.Session>` object. In particular,128:class:`Session <requests.Session>`-level state such as cookies will129not get applied to your request. To get aMerge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8
line 130why, one step back130:class:`PreparedRequest <requests.PreparedRequest>` with that stateMerge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 131–133why, one step back131applied, replace the call to :meth:`Request.prepare()132<requests.Request.prepare>` with a call to133:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 134–137why, one step back134135 from requests import Request, Session136137 s = Session()further cleanup examplesKenneth Reitzbefore adoptionebdd5ca
lines 138–142why, one step back138 req = Request('GET', url,139 data=data140 headers=headers141 )142Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 143why, one step back143 prepped = s.prepare_request(req)further cleanup examplesKenneth Reitzbefore adoptionebdd5ca
line 144why, one step back144Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 145–146why, one step back145 # do something with prepped.body146 # do something with prepped.headersfurther cleanup examplesKenneth Reitzbefore adoptionebdd5ca
line 147why, one step back147Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
line 148why, one step back148 resp = s.send(prepped,further cleanup examplesKenneth Reitzbefore adoptionebdd5ca
lines 149–155why, one step back149 stream=stream,150 verify=verify,151 proxies=proxies,152 cert=cert,153 timeout=timeout154 )155Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc
lines 156–157why, one step back156 print(resp.status_code)157Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3
lines 158–159why, one step back158.. _verification:159try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 160–162why, one step back160SSL Cert Verification161---------------------162Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 163–164why, one step back163Requests can verify SSL certificates for HTTPS requests, just like a web browser.164To check a host's SSL certificate, you can use the ``verify`` argument::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 165–173why, one step back165166 >>> requests.get('https://kennethreitz.com', verify=True)167 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'168169I don't have SSL setup on this domain, so it fails. Excellent. GitHub does though::170171 >>> requests.get('https://github.com', verify=True)172 <Response [200]>173Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81
line 174why, one step back174You can pass ``verify`` the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 175–184why, one step back175176Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.177178::179180 >>> requests.get('https://kennethreitz.com', verify=False)181 <Response [200]>182183By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.184Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 185–187why, one step back185You can also specify a local cert to use as client side certificate, as a single186file (containing the private key and the certificate) or as a tuple of both187file's path::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 188–196why, one step back188189 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))190 <Response [200]>191192If you specify a wrong path or an invalid cert::193194 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')195 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib196Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 197why, one step back197.. _body-content-workflow:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 198–201why, one step back198199Body Content Workflow200---------------------201Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
line 202why, one step back202By default, when you make a request, the body of the response is downloadedMerge pull request #2187 from kevinburke/more-docsKenneth Reitzbefore adoption07bbe21
line 203why, one step back203immediately. You can override this behaviour and defer downloading the responseMerge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 204–205why, one step back204body until you access the :class:`Response.content <requests.Response.content>`205attribute with the ``stream`` parameter::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 206–209why, one step back206207 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'208 r = requests.get(tarball_url, stream=True)209Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 210–211why, one step back210At this point only the response headers have been downloaded and the connection211remains open, hence allowing us to make content retrieval conditional::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 212–216why, one step back212213 if int(r.headers['content-length']) < TOO_LONG:214 content = r.content215 ...216Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 217–221why, one step back217You can further control the workflow by use of the :class:`Response.iter_content <requests.Response.iter_content>`218and :class:`Response.iter_lines <requests.Response.iter_lines>` methods.219Alternatively, you can read the undecoded body from the underlying220urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at221:class:`Response.raw <requests.Response.raw>`.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 222why, one step back222Merge pull request #1867 from Lukasa/closingKenneth Reitzbefore adoption57c71ec
lines 223–236why, one step back223If you set ``stream`` to ``True`` when making a request, Requests cannot224release the connection back to the pool unless you consume all the data or call225:class:`Response.close <requests.Response.close>`. This can lead to226inefficiency with connections. If you find yourself partially reading request227bodies (or not reading them at all) while using ``stream=True``, you should228consider using ``contextlib.closing`` (`documented here`_), like this::229230 from contextlib import closing231232 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:233 # Do things with the response here.234235.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing236Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 237why, one step back237.. _keep-alive:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 238–241why, one step back238239Keep-Alive240----------241Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 242–244why, one step back242Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!243Any requests that you make within a session will automatically reuse the appropriate244connection!try gumroad overlayKenneth Reitzbefore adoption592fb34
line 245why, one step back245Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 246–248why, one step back246Note that connections are only released back to the pool for reuse once all body247data has been read; be sure to either set ``stream`` to ``False`` or read the248``content`` property of the ``Response`` object.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 249why, one step back249Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 250why, one step back250.. _streaming-uploads:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 251–254why, one step back251252Streaming Uploads253-----------------254Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 255–257why, one step back255Requests supports streaming uploads, which allow you to send large streams or256files without reading them into memory. To stream and upload, simply provide a257file-like object for your body::try gumroad overlayKenneth Reitzbefore adoption592fb34
line 258why, one step back258Merge pull request #2074 from Lukasa/filedocCory Benfieldbefore adoption785e4ab
line 259why, one step back259 with open('massive-body', 'rb') as f:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 260–261why, one step back260 requests.post('http://some.url/streamed', data=f)261Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 262why, one step back262.. _chunk-encoding:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 263–266why, one step back263264Chunk-Encoded Requests265----------------------266Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 267–269why, one step back267Requests also supports Chunked transfer encoding for outgoing and incoming requests.268To send a chunk-encoded request, simply provide a generator (or any iterator without269a length) for your body::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 270–278why, one step back270271272 def gen():273 yield 'hi'274 yield 'there'275276 requests.post('http://some.url/chunked', data=gen())277278Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 279why, one step back279.. _multipart:Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0
lines 280–302why, one step back280281POST Multiple Multipart-Encoded Files282-------------------------------------283284You can send multiple files in one request. For example, suppose you want to285upload image files to an HTML form with a multiple file field 'images':286287 <input type="file" name="images" multiple="true" required="true"/>288289To do that, just set files to a list of tuples of (form_field_name, file_info):290291 >>> url = 'http://httpbin.org/post'292 >>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),293 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]294 >>> r = requests.post(url, files=multiple_files)295 >>> r.text296 {297 ...298 'files': {'images': 'data:image/png;base64,iVBORw ....'}299 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',300 ...301 }302Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 303why, one step back303.. _event-hooks:Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0
line 304why, one step back304try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 305–342why, one step back305Event Hooks306-----------307308Requests has a hook system that you can use to manipulate portions of309the request process, or signal event handling.310311Available hooks:312313``response``:314 The response generated from a Request.315316317You can assign a hook function on a per-request basis by passing a318``{hook_name: callback_function}`` dictionary to the ``hooks`` request319parameter::320321 hooks=dict(response=print_url)322323That ``callback_function`` will receive a chunk of data as its first324argument.325326::327328 def print_url(r, *args, **kwargs):329 print(r.url)330331If an error occurs while executing your callback, a warning is given.332333If the callback function returns a value, it is assumed that it is to334replace the data that was passed in. If the function doesn't return335anything, nothing else is effected.336337Let's print some request method arguments at runtime::338339 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))340 http://httpbin.org341 <Response [200]>342Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 343why, one step back343.. _custom-auth:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 344–379why, one step back344345Custom Authentication346---------------------347348Requests allows you to use specify your own authentication mechanism.349350Any callable which is passed as the ``auth`` argument to a request method will351have the opportunity to modify the request before it is dispatched.352353Authentication implementations are subclasses of ``requests.auth.AuthBase``,354and are easy to define. Requests provides two common authentication scheme355implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.356357Let's pretend that we have a web service that will only respond if the358``X-Pizza`` header is set to a password value. Unlikely, but just go with it.359360::361362 from requests.auth import AuthBase363364 class PizzaAuth(AuthBase):365 """Attaches HTTP Pizza Authentication to the given Request object."""366 def __init__(self, username):367 # setup any auth-related data here368 self.username = username369370 def __call__(self, r):371 # modify and return the request372 r.headers['X-Pizza'] = self.username373 return r374375Then, we can make a request using our Pizza Auth::376377 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))378 <Response [200]>379Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
line 380why, one step back380.. _streaming-requests:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 381–384why, one step back381382Streaming Requests383------------------384Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 385–386why, one step back385With :class:`requests.Response.iter_lines()` you can easily386iterate over streaming APIs such as the `Twitter StreamingMerge pull request #2374 from krvc/fix_linkIan Cordascobefore adoptione23bf10
line 387why, one step back387API <https://dev.twitter.com/streaming/overview>`_. SimplyMerge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 388–389why, one step back388set ``stream`` to ``True`` and iterate over the response with389:class:`~requests.Response.iter_lines()`::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 390–399why, one step back390391 import json392 import requests393394 r = requests.get('http://httpbin.org/stream/20', stream=True)395396 for line in r.iter_lines():397398 # filter out keep-alive new lines399 if line:Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 400why, one step back400 print(json.loads(line))try gumroad overlayKenneth Reitzbefore adoption592fb34
line 401why, one step back401Merge pull request #2348 from danmichaelo/masterKenneth Reitzbefore adoption8ae4d02
line 402why, one step back402.. _proxies:try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 403–448why, one step back403404Proxies405-------406407If you need to use a proxy, you can configure individual requests with the408``proxies`` argument to any request method::409410 import requests411412 proxies = {413 "http": "http://10.10.1.10:3128",414 "https": "http://10.10.1.10:1080",415 }416417 requests.get("http://example.org", proxies=proxies)418419You can also configure proxies by setting the environment variables420``HTTP_PROXY`` and ``HTTPS_PROXY``.421422::423424 $ export HTTP_PROXY="http://10.10.1.10:3128"425 $ export HTTPS_PROXY="http://10.10.1.10:1080"426 $ python427 >>> import requests428 >>> requests.get("http://example.org")429430To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::431432 proxies = {433 "http": "http://user:pass@10.10.1.10:3128/",434 }435436Note that proxy URLs must include the scheme.437438Compliance439----------440441Requests is intended to be compliant with all relevant specifications and442RFCs where that compliance will not cause difficulties for users. This443attention to the specification can lead to some behaviour that may seem444unusual to those not familiar with the relevant specification.445446Encodings447^^^^^^^^^448Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 449–453why, one step back449When you receive a response, Requests makes a guess at the encoding to450use for decoding the response when you access the :attr:`Response.text451<requests.Response.text>` attribute. Requests will first check for an452encoding in the HTTP header, and if none is present, will use `chardet453<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 454why, one step back454Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 455–462why, one step back455The only time Requests will not do this is if no explicit charset456is present in the HTTP headers **and** the ``Content-Type``457header contains ``text``. In this situation, `RFC 2616458<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies459that the default charset must be ``ISO-8859-1``. Requests follows the460specification in this case. If you require a different encoding, you can461manually set the :attr:`Response.encoding <requests.Response.encoding>`462property, or use the raw :attr:`Response.content <requests.Response.content>`.try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 463–483why, one step back463464HTTP Verbs465----------466467Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,468HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of469using these various verbs in Requests, using the GitHub API.470471We will begin with the verb most commonly used: GET. HTTP GET is an idempotent472method that returns a resource from a given URL. As a result, it is the verb473you ought to use when attempting to retrieve data from a web location. An474example usage would be attempting to get information about a specific commit475from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it476like so::477478 >>> import requests479 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')480481We should confirm that GitHub responded correctly. If it has, we want to work482out what type of content it is. Do this like so::483Merge pull request #2134 from nonZero/patch-1Ian Cordascobefore adoptiond21916c
line 484why, one step back484 >>> if r.status_code == requests.codes.ok:Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 485why, one step back485 ... print(r.headers['content-type'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 486–488why, one step back486 ...487 application/json; charset=utf-8488Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 489–490why, one step back489So, GitHub returns JSON. That's great, we can use the :meth:`r.json490<requests.Response.json>` method to parse it into Python objects.try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 491–494why, one step back491492::493494 >>> commit_data = r.json()Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 495why, one step back495 >>> print(commit_data.keys())try gumroad overlayKenneth Reitzbefore adoption592fb34
line 496why, one step back496 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 497why, one step back497 >>> print(commit_data[u'committer'])try gumroad overlayKenneth Reitzbefore adoption592fb34
line 498why, one step back498 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 499why, one step back499 >>> print(commit_data[u'message'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 500–521why, one step back500 makin' history501502So far, so simple. Well, let's investigate the GitHub API a little bit. Now,503we could look at the documentation, but we might have a little more fun if we504use Requests instead. We can take advantage of the Requests OPTIONS verb to505see what kinds of HTTP methods are supported on the url we just used.506507::508509 >>> verbs = requests.options(r.url)510 >>> verbs.status_code511 500512513Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't514actually implement the OPTIONS method. This is an annoying oversight, but it's515OK, we can just use the boring documentation. If GitHub had correctly516implemented OPTIONS, however, they should return the allowed methods in the517headers, e.g.518519::520521 >>> verbs = requests.options('http://a-good-website.com/api/cats')Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 522why, one step back522 >>> print(verbs.headers['allow'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 523–538why, one step back523 GET,HEAD,POST,OPTIONS524525Turning to the documentation, we see that the only other method allowed for526commits is POST, which creates a new commit. As we're using the Requests repo,527we should probably avoid making ham-handed POSTS to it. Instead, let's play528with the Issues feature of GitHub.529530This documentation was added in response to Issue #482. Given that this issue531already exists, we will use it as an example. Let's start by getting it.532533::534535 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')536 >>> r.status_code537 200538 >>> issue = json.loads(r.text)Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 539why, one step back539 >>> print(issue[u'title'])try gumroad overlayKenneth Reitzbefore adoption592fb34
line 540why, one step back540 Feature any http verb in docsMerge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 541why, one step back541 >>> print(issue[u'comments'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 542–551why, one step back542 3543544Cool, we have three comments. Let's take a look at the last of them.545546::547548 >>> r = requests.get(r.url + u'/comments')549 >>> r.status_code550 200551 >>> comments = r.json()Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 552why, one step back552 >>> print(comments[0].keys())try gumroad overlayKenneth Reitzbefore adoption592fb34
line 553why, one step back553 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 554why, one step back554 >>> print(comments[2][u'body'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 555–561why, one step back555 Probably in the "advanced" section556557Well, that seems like a silly place. Let's post a comment telling the poster558that he's silly. Who is the poster, anyway?559560::561Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 562why, one step back562 >>> print(comments[2][u'user'][u'login'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 563–588why, one step back563 kennethreitz564565OK, so let's tell this Kenneth guy that we think this example should go in the566quickstart guide instead. According to the GitHub API doc, the way to do this567is to POST to the thread. Let's do it.568569::570571 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})572 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"573 >>> r = requests.post(url=url, data=body)574 >>> r.status_code575 404576577Huh, that's weird. We probably need to authenticate. That'll be a pain, right?578Wrong. Requests makes it easy to use many forms of authentication, including579the very common Basic Auth.580581::582583 >>> from requests.auth import HTTPBasicAuth584 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')585 >>> r = requests.post(url=url, data=body, auth=auth)586 >>> r.status_code587 201588 >>> content = r.json()Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 589why, one step back589 >>> print(content[u'body'])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 590–598why, one step back590 Sounds great! I'll get right on it.591592Brilliant. Oh, wait, no! I meant to add that it would take me a while, because593I had to go feed my cat. If only I could edit this comment! Happily, GitHub594allows us to use another HTTP verb, PATCH, to edit this comment. Let's do595that.596597::598Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 599why, one step back599 >>> print(content[u"id"])try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 600–627why, one step back600 5804413601 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})602 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"603 >>> r = requests.patch(url=url, data=body, auth=auth)604 >>> r.status_code605 200606607Excellent. Now, just to torture this Kenneth guy, I've decided to let him608sweat and not tell him that I'm working on this. That means I want to delete609this comment. GitHub lets us delete comments using the incredibly aptly named610DELETE method. Let's get rid of it.611612::613614 >>> r = requests.delete(url=url, auth=auth)615 >>> r.status_code616 204617 >>> r.headers['status']618 '204 No Content'619620Excellent. All gone. The last thing I want to know is how much of my ratelimit621I've used. Let's find out. GitHub sends that information in the headers, so622rather than download the whole page I'll send a HEAD request to get the623headers.624625::626627 >>> r = requests.head(url=url, auth=auth)Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a
line 628why, one step back628 >>> print(r.headers)try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 629–639why, one step back629 ...630 'x-ratelimit-remaining': '4995'631 'x-ratelimit-limit': '5000'632 ...633634Excellent. Time to write a Python program that abuses the GitHub API in all635kinds of exciting ways, 4995 more times.636637Link Headers638------------639Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 640–641why, one step back640Many HTTP APIs feature Link headers. They make APIs more self describing and641discoverable.try gumroad overlayKenneth Reitzbefore adoption592fb34
line 642why, one step back642Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282
lines 643–644why, one step back643GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_644in their API, for example::try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 645–667why, one step back645646 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'647 >>> r = requests.head(url=url)648 >>> r.headers['link']649 '<https://api.github.com/users/kennethreitz/repos?page=2&per_page=10>; rel="next", <https://api.github.com/users/kennethreitz/repos?page=6&per_page=10>; rel="last"'650651Requests will automatically parse these link headers and make them easily consumable::652653 >>> r.links["next"]654 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}655656 >>> r.links["last"]657 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}658659Transport Adapters660------------------661662As of v1.0.0, Requests has moved to a modular internal design. Part of the663reason this was done was to implement Transport Adapters, originally664`described here`_. Transport Adapters provide a mechanism to define interaction665methods for an HTTP service. In particular, they allow you to apply per-service666configuration.667Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 668–672why, one step back668Requests ships with a single Transport Adapter, the :class:`HTTPAdapter669<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests670interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever671a Requests :class:`Session <requests.Session>` is initialized, one of these is672attached to the :class:`Session <requests.Session>` object for HTTP, and onetry gumroad overlayKenneth Reitzbefore adoption592fb34
lines 673–688why, one step back673for HTTPS.674675Requests enables users to create and use their own Transport Adapters that676provide specific functionality. Once created, a Transport Adapter can be677mounted to a Session object, along with an indication of which web services678it should apply to.679680::681682 >>> s = requests.Session()683 >>> s.mount('http://www.github.com', MyAdapter())684685The mount call registers a specific instance of a Transport Adapter to a686prefix. Once mounted, any HTTP request made using that session whose URL starts687with the given prefix will use the given Transport Adapter.688Merge branch 'master' of github.com:dsoprea/requestsCory Benfieldbefore adoption0988651
lines 689–694why, one step back689Many of the details of implementing a Transport Adapter are beyond the scope of690this documentation, but take a look at the next example for a simple SSL use-691case. For more than that, you might look at subclassing692``requests.adapters.BaseAdapter``.693694Example: Specific SSL VersionFixup the header heirarchy.Cory Benfieldbefore adoptionac4e058
line 695why, one step back695^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Merge branch 'master' of github.com:dsoprea/requestsCory Benfieldbefore adoption0988651
lines 696–722why, one step back696697The Requests team has made a specific choice to use whatever SSL version is698default in the underlying library (`urllib3`_). Normally this is fine, but from699time to time, you might find yourself needing to connect to a service-endpoint700that uses a version that isn't compatible with the default.701702You can use Transport Adapters for this by taking most of the existing703implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets704passed-through to `urllib3`. We'll make a TA that instructs the library to use705SSLv3:706707::708709 import ssl710711 from requests.adapters import HTTPAdapter712 from requests.packages.urllib3.poolmanager import PoolManager713714715 class Ssl3HttpAdapter(HTTPAdapter):716 """"Transport adapter" that allows us to use SSLv3."""717718 def init_poolmanager(self, connections, maxsize, block=False):719 self.poolmanager = PoolManager(num_pools=connections,720 maxsize=maxsize,721 block=block,722 ssl_version=ssl.PROTOCOL_SSLv3)try gumroad overlayKenneth Reitzbefore adoption592fb34
line 723why, one step back723Merge pull request #2128 from tshepang/patch-1Ian Cordascobefore adoption28d1ef5
line 724why, one step back724.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-httptry gumroad overlayKenneth Reitzbefore adoption592fb34
lines 725–730why, one step back725.. _`urllib3`: https://github.com/shazow/urllib3726727Blocking Or Non-Blocking?728-------------------------729730With the default Transport Adapter in place, Requests does not provide any kindMerge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233
lines 731–735why, one step back731of non-blocking IO. The :attr:`Response.content <requests.Response.content>`732property will block until the entire response has been downloaded. If733you require more granularity, the streaming features of the library (see734:ref:`streaming-requests`) allow you to retrieve smaller quantities of the735response at a time. However, these calls will still block.try gumroad overlayKenneth Reitzbefore adoption592fb34
lines 736–742why, one step back736737If you are concerned about the use of blocking IO, there are lots of projects738out there that combine Requests with one of Python's asynchronicity frameworks.739Two excellent examples are `grequests`_ and `requests-futures`_.740741.. _`grequests`: https://github.com/kennethreitz/grequests742.. _`requests-futures`: https://github.com/ross/requests-futuresMerge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a
lines 743–780why, one step back743744Timeouts745--------746747Most requests to external servers should have a timeout attached, in case the748server is not responding in a timely manner. Without a timeout, your code may749hang for minutes or more.750751The **connect** timeout is the number of seconds Requests will wait for your752client to establish a connection to a remote machine (corresponding to the753`connect()`_) call on the socket. It's a good practice to set connect timeouts754to slightly larger than a multiple of 3, which is the default `TCP packet755retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.756757Once your client has connected to the server and sent the HTTP request, the758**read** timeout is the number of seconds the client will wait for the server759to send a response. (Specifically, it's the number of seconds that the client760will wait *between* bytes sent from the server. In 99.9% of cases, this is the761time before the server sends the first byte).762763If you specify a single value for the timeout, like this::764765 r = requests.get('https://github.com', timeout=5)766767The timeout value will be applied to both the ``connect`` and the ``read``768timeouts. Specify a tuple if you would like to set the values separately::769770 r = requests.get('https://github.com', timeout=(3.05, 27))771772If the remote server is very slow, you can tell Requests to wait forever for773a response, by passing None as a timeout value and then retrieving a cup of774coffee.775776.. code-block:: python777778 r = requests.get('https://github.com', timeout=None)779780.. _`connect()`: http://linux.die.net/man/2/connectMerge pull request #2203 from Lukasa/remove_certifiKenneth Reitzbefore adoption359659c
lines 781–798why, one step back781782CA Certificates783---------------784785By default Requests bundles a set of root CAs that it trusts, sourced from the786`Mozilla trust store`_. However, these are only updated once for each Requests787version. This means that if you pin a Requests version your certificates can788become extremely out of date.789790From Requests version 2.4.0 onwards, Requests will attempt to use certificates791from `certifi`_ if it is present on the system. This allows for users to update792their trusted certificates without having to change the code that runs on their793system.794795For the sake of security we recommend upgrading certifi frequently!796797.. _certifi: http://certifi.io/798.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt