Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

785 lines · 27.5 KiB

Last changed by

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

History of this file

Take it

The walk stopped after 200 commits: lines older than afa7594 point at it.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 1–39why, one step back
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.text)26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods. This30is done by providing data to the properties on a Session object::3132 s = requests.Session()33 s.auth = ('user', 'pass')34 s.headers.update({'x-test': 'true'})3536 # both 'x-test' and 'x-test2' are sent37 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})3839

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 40–42why, one step back
40Any dictionaries that you pass to a request method will be merged with the
41session-level values that are set. The method-level parameters override session42parameters.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 43–45why, one step back
43
44.. admonition:: Remove a Value From a Dict Parameter45

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 46–48why, one step back
46 Sometimes you'll want to omit session-level keys from a dict parameter. To
47 do this, you simply set that key's value to ``None`` in the method-level48 parameter. It will automatically be omitted.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 49why, one step back
49

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 50–51why, one step back
50All values that are contained within a session are directly available to you.
51See the :ref:`Session API Docs <sessionapi>` to learn more.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 52–87why, one step back
52
53Request and Response Objects54----------------------------5556Whenever a call is made to ``requests.get()`` and friends you are doing two57major things. First, you are constructing a ``Request`` object which will be58sent off to a server to request or query some resource. Second, a ``Response``59object is generated once ``requests`` gets a response back from the server.60The Response object contains all of the information returned by the server and61also contains the ``Request`` object you created originally. Here is a simple62request to get some very important information from Wikipedia's servers::6364 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')6566If we want to access the headers the server sent back to us, we do this::6768 >>> r.headers69 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':70 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':71 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',72 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',73 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,74 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':75 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,76 MISS from cp1010.eqiad.wmnet:80'}7778However, if we want to get the headers we sent the server, we simply access the79request, and then the request's headers::8081 >>> r.request.headers82 {'Accept-Encoding': 'identity, deflate, compress, gzip',83 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}8485Prepared Requests86-----------------87

Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8

line 88why, one step back
88Whenever you receive a :class:`Response <requests.Response>` object

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 89–96why, one step back
89from an API call or a Session call, the ``request`` attribute is actually the
90``PreparedRequest`` that was used. In some cases you may wish to do some extra91work to the body or headers (or anything else really) before sending a92request. The simple recipe for this is the following::9394 from requests import Request, Session9596 s = Session()

fix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b

lines 97–102why, one step back
97 req = Request('GET', url,
98 data=data,99 headers=header100 )101 prepped = req.prepare()102

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 103–104why, one step back
103 # do something with prepped.body
104 # do something with prepped.headers

fix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b

line 105why, one step back
105

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 106why, one step back
106 resp = s.send(prepped,

fix @lukasa's lack of taste :)Kenneth Reitzbefore adoption2c1f51b

lines 107–113why, one step back
107 stream=stream,
108 verify=verify,109 proxies=proxies,110 cert=cert,111 timeout=timeout112 )113

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 114–116why, one step back
114 print(resp.status_code)
115116Since you are not doing anything special with the ``Request`` object, you

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

line 117why, one step back
117prepare it immediately and modify the ``PreparedRequest`` object. You then

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 118why, one step back
118send that with the other parameters you would have sent to ``requests.*`` or

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption343db40

line 119why, one step back
119``Session.*``.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 120why, one step back
120

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

lines 121–124why, one step back
121However, the above code will lose some of the advantages of having a Requests
122:class:`Session <requests.Session>` object. In particular,123:class:`Session <requests.Session>`-level state such as cookies will124not get applied to your request. To get a

Merge pull request #2135 from dpursehouse/fix-meth-and-class-directivesCory Benfieldbefore adoptione25fbc8

line 125why, one step back
125:class:`PreparedRequest <requests.PreparedRequest>` with that state

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 126–128why, one step back
126applied, replace the call to :meth:`Request.prepare()
127<requests.Request.prepare>` with a call to128:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

lines 129–132why, one step back
129
130 from requests import Request, Session131132 s = Session()

further cleanup examplesKenneth Reitzbefore adoptionebdd5ca

lines 133–137why, one step back
133 req = Request('GET', url,
134 data=data135 headers=headers136 )137

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

line 138why, one step back
138 prepped = s.prepare_request(req)

further cleanup examplesKenneth Reitzbefore adoptionebdd5ca

line 139why, one step back
139

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

lines 140–141why, one step back
140 # do something with prepped.body
141 # do something with prepped.headers

further cleanup examplesKenneth Reitzbefore adoptionebdd5ca

line 142why, one step back
142

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

line 143why, one step back
143 resp = s.send(prepped,

further cleanup examplesKenneth Reitzbefore adoptionebdd5ca

lines 144–150why, one step back
144 stream=stream,
145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona9839dc

lines 151–152why, one step back
151 print(resp.status_code)
152

Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptiona3cd2f3

lines 153–154why, one step back
153.. _verification:
154

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 155–157why, one step back
155SSL Cert Verification
156---------------------157

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 158–159why, one step back
158Requests can verify SSL certificates for HTTPS requests, just like a web browser.
159To check a host's SSL certificate, you can use the ``verify`` argument::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 160–168why, one step back
160
161 >>> requests.get('https://kennethreitz.com', verify=True)162 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'163164I don't have SSL setup on this domain, so it fails. Excellent. GitHub does though::165166 >>> requests.get('https://github.com', verify=True)167 <Response [200]>168

Merge pull request #2248 from jktjkt/docs-CAsCory Benfieldbefore adoptiona718a81

line 169why, one step back
169You 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.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 170–179why, one step back
170
171Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.172173::174175 >>> requests.get('https://kennethreitz.com', verify=False)176 <Response [200]>177178By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.179

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 180–182why, one step back
180You can also specify a local cert to use as client side certificate, as a single
181file (containing the private key and the certificate) or as a tuple of both182file's path::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 183–195why, one step back
183
184 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))185 <Response [200]>186187If you specify a wrong path or an invalid cert::188189 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')190 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib191192193Body Content Workflow194---------------------195

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

line 196why, one step back
196By default, when you make a request, the body of the response is downloaded

Merge pull request #2187 from kevinburke/more-docsKenneth Reitzbefore adoption07bbe21

line 197why, one step back
197immediately. You can override this behaviour and defer downloading the response

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 198–199why, one step back
198body until you access the :class:`Response.content <requests.Response.content>`
199attribute with the ``stream`` parameter::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 200–203why, one step back
200
201 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'202 r = requests.get(tarball_url, stream=True)203

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 204–205why, one step back
204At this point only the response headers have been downloaded and the connection
205remains open, hence allowing us to make content retrieval conditional::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 206–210why, one step back
206
207 if int(r.headers['content-length']) < TOO_LONG:208 content = r.content209 ...210

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 211–215why, one step back
211You can further control the workflow by use of the :class:`Response.iter_content <requests.Response.iter_content>`
212and :class:`Response.iter_lines <requests.Response.iter_lines>` methods.213Alternatively, you can read the undecoded body from the underlying214urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at215:class:`Response.raw <requests.Response.raw>`.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 216why, one step back
216

Merge pull request #1867 from Lukasa/closingKenneth Reitzbefore adoption57c71ec

lines 217–230why, one step back
217If you set ``stream`` to ``True`` when making a request, Requests cannot
218release the connection back to the pool unless you consume all the data or call219:class:`Response.close <requests.Response.close>`. This can lead to220inefficiency with connections. If you find yourself partially reading request221bodies (or not reading them at all) while using ``stream=True``, you should222consider using ``contextlib.closing`` (`documented here`_), like this::223224 from contextlib import closing225226 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:227 # Do things with the response here.228229.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing230

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 231–234why, one step back
231
232Keep-Alive233----------234

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 235–237why, one step back
235Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!
236Any requests that you make within a session will automatically reuse the appropriate237connection!

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 238why, one step back
238

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 239–241why, one step back
239Note that connections are only released back to the pool for reuse once all body
240data has been read; be sure to either set ``stream`` to ``False`` or read the241``content`` property of the ``Response`` object.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 242–246why, one step back
242
243244Streaming Uploads245-----------------246

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 247–249why, one step back
247Requests supports streaming uploads, which allow you to send large streams or
248files without reading them into memory. To stream and upload, simply provide a249file-like object for your body::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 250why, one step back
250

Merge pull request #2074 from Lukasa/filedocCory Benfieldbefore adoption785e4ab

line 251why, one step back
251 with open('massive-body', 'rb') as f:

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 252–257why, one step back
252 requests.post('http://some.url/streamed', data=f)
253254255Chunk-Encoded Requests256----------------------257

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 258–260why, one step back
258Requests also supports Chunked transfer encoding for outgoing and incoming requests.
259To send a chunk-encoded request, simply provide a generator (or any iterator without260a length) for your body::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 261–269why, one step back
261
262263 def gen():264 yield 'hi'265 yield 'there'266267 requests.post('http://some.url/chunked', data=gen())268269

Merge pull request #2227 from mjul/masterKenneth Reitzbefore adoption082c8d0

lines 270–293why, one step back
270
271POST Multiple Multipart-Encoded Files272-------------------------------------273274You can send multiple files in one request. For example, suppose you want to275upload image files to an HTML form with a multiple file field 'images':276277 <input type="file" name="images" multiple="true" required="true"/>278279To do that, just set files to a list of tuples of (form_field_name, file_info):280281 >>> url = 'http://httpbin.org/post'282 >>> multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),283 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]284 >>> r = requests.post(url, files=multiple_files)285 >>> r.text286 {287 ...288 'files': {'images': 'data:image/png;base64,iVBORw ....'}289 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',290 ...291 }292293

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 294–367why, one step back
294Event Hooks
295-----------296297Requests has a hook system that you can use to manipulate portions of298the request process, or signal event handling.299300Available hooks:301302``response``:303 The response generated from a Request.304305306You can assign a hook function on a per-request basis by passing a307``{hook_name: callback_function}`` dictionary to the ``hooks`` request308parameter::309310 hooks=dict(response=print_url)311312That ``callback_function`` will receive a chunk of data as its first313argument.314315::316317 def print_url(r, *args, **kwargs):318 print(r.url)319320If an error occurs while executing your callback, a warning is given.321322If the callback function returns a value, it is assumed that it is to323replace the data that was passed in. If the function doesn't return324anything, nothing else is effected.325326Let's print some request method arguments at runtime::327328 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))329 http://httpbin.org330 <Response [200]>331332333Custom Authentication334---------------------335336Requests allows you to use specify your own authentication mechanism.337338Any callable which is passed as the ``auth`` argument to a request method will339have the opportunity to modify the request before it is dispatched.340341Authentication implementations are subclasses of ``requests.auth.AuthBase``,342and are easy to define. Requests provides two common authentication scheme343implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.344345Let's pretend that we have a web service that will only respond if the346``X-Pizza`` header is set to a password value. Unlikely, but just go with it.347348::349350 from requests.auth import AuthBase351352 class PizzaAuth(AuthBase):353 """Attaches HTTP Pizza Authentication to the given Request object."""354 def __init__(self, username):355 # setup any auth-related data here356 self.username = username357358 def __call__(self, r):359 # modify and return the request360 r.headers['X-Pizza'] = self.username361 return r362363Then, we can make a request using our Pizza Auth::364365 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))366 <Response [200]>367

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

line 368why, one step back
368.. _streaming-requests:

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 369–372why, one step back
369
370Streaming Requests371------------------372

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 373–377why, one step back
373With :class:`requests.Response.iter_lines()` you can easily
374iterate over streaming APIs such as the `Twitter Streaming375API <https://dev.twitter.com/docs/streaming-api>`_. Simply376set ``stream`` to ``True`` and iterate over the response with377:class:`~requests.Response.iter_lines()`::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 378–387why, one step back
378
379 import json380 import requests381382 r = requests.get('http://httpbin.org/stream/20', stream=True)383384 for line in r.iter_lines():385386 # filter out keep-alive new lines387 if line:

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 388why, one step back
388 print(json.loads(line))

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 389–435why, one step back
389
390391Proxies392-------393394If you need to use a proxy, you can configure individual requests with the395``proxies`` argument to any request method::396397 import requests398399 proxies = {400 "http": "http://10.10.1.10:3128",401 "https": "http://10.10.1.10:1080",402 }403404 requests.get("http://example.org", proxies=proxies)405406You can also configure proxies by setting the environment variables407``HTTP_PROXY`` and ``HTTPS_PROXY``.408409::410411 $ export HTTP_PROXY="http://10.10.1.10:3128"412 $ export HTTPS_PROXY="http://10.10.1.10:1080"413 $ python414 >>> import requests415 >>> requests.get("http://example.org")416417To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::418419 proxies = {420 "http": "http://user:pass@10.10.1.10:3128/",421 }422423Note that proxy URLs must include the scheme.424425Compliance426----------427428Requests is intended to be compliant with all relevant specifications and429RFCs where that compliance will not cause difficulties for users. This430attention to the specification can lead to some behaviour that may seem431unusual to those not familiar with the relevant specification.432433Encodings434^^^^^^^^^435

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 436–440why, one step back
436When you receive a response, Requests makes a guess at the encoding to
437use for decoding the response when you access the :attr:`Response.text438<requests.Response.text>` attribute. Requests will first check for an439encoding in the HTTP header, and if none is present, will use `chardet440<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 441why, one step back
441

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 442–449why, one step back
442The only time Requests will not do this is if no explicit charset
443is present in the HTTP headers **and** the ``Content-Type``444header contains ``text``. In this situation, `RFC 2616445<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies446that the default charset must be ``ISO-8859-1``. Requests follows the447specification in this case. If you require a different encoding, you can448manually set the :attr:`Response.encoding <requests.Response.encoding>`449property, or use the raw :attr:`Response.content <requests.Response.content>`.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 450–470why, one step back
450
451HTTP Verbs452----------453454Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,455HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of456using these various verbs in Requests, using the GitHub API.457458We will begin with the verb most commonly used: GET. HTTP GET is an idempotent459method that returns a resource from a given URL. As a result, it is the verb460you ought to use when attempting to retrieve data from a web location. An461example usage would be attempting to get information about a specific commit462from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it463like so::464465 >>> import requests466 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')467468We should confirm that GitHub responded correctly. If it has, we want to work469out what type of content it is. Do this like so::470

Merge pull request #2134 from nonZero/patch-1Ian Cordascobefore adoptiond21916c

line 471why, one step back
471 >>> if r.status_code == requests.codes.ok:

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 472why, one step back
472 ... print(r.headers['content-type'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 473–475why, one step back
473 ...
474 application/json; charset=utf-8475

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 476–477why, one step back
476So, GitHub returns JSON. That's great, we can use the :meth:`r.json
477<requests.Response.json>` method to parse it into Python objects.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 478–481why, one step back
478
479::480481 >>> commit_data = r.json()

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 482why, one step back
482 >>> print(commit_data.keys())

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 483why, one step back
483 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 484why, one step back
484 >>> print(commit_data[u'committer'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 485why, one step back
485 {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 486why, one step back
486 >>> print(commit_data[u'message'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 487–508why, one step back
487 makin' history
488489So far, so simple. Well, let's investigate the GitHub API a little bit. Now,490we could look at the documentation, but we might have a little more fun if we491use Requests instead. We can take advantage of the Requests OPTIONS verb to492see what kinds of HTTP methods are supported on the url we just used.493494::495496 >>> verbs = requests.options(r.url)497 >>> verbs.status_code498 500499500Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't501actually implement the OPTIONS method. This is an annoying oversight, but it's502OK, we can just use the boring documentation. If GitHub had correctly503implemented OPTIONS, however, they should return the allowed methods in the504headers, e.g.505506::507508 >>> verbs = requests.options('http://a-good-website.com/api/cats')

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 509why, one step back
509 >>> print(verbs.headers['allow'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 510–525why, one step back
510 GET,HEAD,POST,OPTIONS
511512Turning to the documentation, we see that the only other method allowed for513commits is POST, which creates a new commit. As we're using the Requests repo,514we should probably avoid making ham-handed POSTS to it. Instead, let's play515with the Issues feature of GitHub.516517This documentation was added in response to Issue #482. Given that this issue518already exists, we will use it as an example. Let's start by getting it.519520::521522 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')523 >>> r.status_code524 200525 >>> issue = json.loads(r.text)

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 526why, one step back
526 >>> print(issue[u'title'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 527why, one step back
527 Feature any http verb in docs

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 528why, one step back
528 >>> print(issue[u'comments'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 529–538why, one step back
529 3
530531Cool, we have three comments. Let's take a look at the last of them.532533::534535 >>> r = requests.get(r.url + u'/comments')536 >>> r.status_code537 200538 >>> comments = r.json()

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 539why, one step back
539 >>> print(comments[0].keys())

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 540why, one step back
540 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 541why, one step back
541 >>> print(comments[2][u'body'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 542–548why, one step back
542 Probably in the "advanced" section
543544Well, that seems like a silly place. Let's post a comment telling the poster545that he's silly. Who is the poster, anyway?546547::548

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 549why, one step back
549 >>> print(comments[2][u'user'][u'login'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 550–575why, one step back
550 kennethreitz
551552OK, so let's tell this Kenneth guy that we think this example should go in the553quickstart guide instead. According to the GitHub API doc, the way to do this554is to POST to the thread. Let's do it.555556::557558 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})559 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"560 >>> r = requests.post(url=url, data=body)561 >>> r.status_code562 404563564Huh, that's weird. We probably need to authenticate. That'll be a pain, right?565Wrong. Requests makes it easy to use many forms of authentication, including566the very common Basic Auth.567568::569570 >>> from requests.auth import HTTPBasicAuth571 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')572 >>> r = requests.post(url=url, data=body, auth=auth)573 >>> r.status_code574 201575 >>> content = r.json()

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 576why, one step back
576 >>> print(content[u'body'])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 577–585why, one step back
577 Sounds great! I'll get right on it.
578579Brilliant. Oh, wait, no! I meant to add that it would take me a while, because580I had to go feed my cat. If only I could edit this comment! Happily, GitHub581allows us to use another HTTP verb, PATCH, to edit this comment. Let's do582that.583584::585

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 586why, one step back
586 >>> print(content[u"id"])

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 587–614why, one step back
587 5804413
588 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})589 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"590 >>> r = requests.patch(url=url, data=body, auth=auth)591 >>> r.status_code592 200593594Excellent. Now, just to torture this Kenneth guy, I've decided to let him595sweat and not tell him that I'm working on this. That means I want to delete596this comment. GitHub lets us delete comments using the incredibly aptly named597DELETE method. Let's get rid of it.598599::600601 >>> r = requests.delete(url=url, auth=auth)602 >>> r.status_code603 204604 >>> r.headers['status']605 '204 No Content'606607Excellent. All gone. The last thing I want to know is how much of my ratelimit608I've used. Let's find out. GitHub sends that information in the headers, so609rather than download the whole page I'll send a HEAD request to get the610headers.611612::613614 >>> r = requests.head(url=url, auth=auth)

Merge pull request #2141 from esparta/masterCory Benfieldbefore adoptione66466a

line 615why, one step back
615 >>> print(r.headers)

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 616–626why, one step back
616 ...
617 'x-ratelimit-remaining': '4995'618 'x-ratelimit-limit': '5000'619 ...620621Excellent. Time to write a Python program that abuses the GitHub API in all622kinds of exciting ways, 4995 more times.623624Link Headers625------------626

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 627–628why, one step back
627Many HTTP APIs feature Link headers. They make APIs more self describing and
628discoverable.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 629why, one step back
629

Merge pull request #2139 from dpursehouse/line-wrappingCory Benfieldbefore adoption4c94282

lines 630–631why, one step back
630GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_
631in their API, for example::

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 632–654why, one step back
632
633 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'634 >>> r = requests.head(url=url)635 >>> r.headers['link']636 '<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"'637638Requests will automatically parse these link headers and make them easily consumable::639640 >>> r.links["next"]641 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}642643 >>> r.links["last"]644 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}645646Transport Adapters647------------------648649As of v1.0.0, Requests has moved to a modular internal design. Part of the650reason this was done was to implement Transport Adapters, originally651`described here`_. Transport Adapters provide a mechanism to define interaction652methods for an HTTP service. In particular, they allow you to apply per-service653configuration.654

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 655–659why, one step back
655Requests ships with a single Transport Adapter, the :class:`HTTPAdapter
656<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests657interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever658a Requests :class:`Session <requests.Session>` is initialized, one of these is659attached to the :class:`Session <requests.Session>` object for HTTP, and one

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 660–675why, one step back
660for HTTPS.
661662Requests enables users to create and use their own Transport Adapters that663provide specific functionality. Once created, a Transport Adapter can be664mounted to a Session object, along with an indication of which web services665it should apply to.666667::668669 >>> s = requests.Session()670 >>> s.mount('http://www.github.com', MyAdapter())671672The mount call registers a specific instance of a Transport Adapter to a673prefix. Once mounted, any HTTP request made using that session whose URL starts674with the given prefix will use the given Transport Adapter.675

Merge branch 'master' of github.com:dsoprea/requestsCory Benfieldbefore adoption0988651

lines 676–681why, one step back
676Many of the details of implementing a Transport Adapter are beyond the scope of
677this documentation, but take a look at the next example for a simple SSL use-678case. For more than that, you might look at subclassing679``requests.adapters.BaseAdapter``.680681Example: Specific SSL Version

Fixup the header heirarchy.Cory Benfieldbefore adoptionac4e058

line 682why, one step back
682^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Merge branch 'master' of github.com:dsoprea/requestsCory Benfieldbefore adoption0988651

lines 683–709why, one step back
683
684The Requests team has made a specific choice to use whatever SSL version is685default in the underlying library (`urllib3`_). Normally this is fine, but from686time to time, you might find yourself needing to connect to a service-endpoint687that uses a version that isn't compatible with the default.688689You can use Transport Adapters for this by taking most of the existing690implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets691passed-through to `urllib3`. We'll make a TA that instructs the library to use692SSLv3:693694::695696 import ssl697698 from requests.adapters import HTTPAdapter699 from requests.packages.urllib3.poolmanager import PoolManager700701702 class Ssl3HttpAdapter(HTTPAdapter):703 """"Transport adapter" that allows us to use SSLv3."""704705 def init_poolmanager(self, connections, maxsize, block=False):706 self.poolmanager = PoolManager(num_pools=connections,707 maxsize=maxsize,708 block=block,709 ssl_version=ssl.PROTOCOL_SSLv3)

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

line 710why, one step back
710

Merge pull request #2128 from tshepang/patch-1Ian Cordascobefore adoption28d1ef5

line 711why, one step back
711.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 712–717why, one step back
712.. _`urllib3`: https://github.com/shazow/urllib3
713714Blocking Or Non-Blocking?715-------------------------716717With the default Transport Adapter in place, Requests does not provide any kind

Merge branch 'master' into fix-pickling-adaptersKenneth Reitzbefore adoptiondf1c233

lines 718–722why, one step back
718of non-blocking IO. The :attr:`Response.content <requests.Response.content>`
719property will block until the entire response has been downloaded. If720you require more granularity, the streaming features of the library (see721:ref:`streaming-requests`) allow you to retrieve smaller quantities of the722response at a time. However, these calls will still block.

build status isn't useful anywayKenneth Reitzbefore adoptionafa7594

lines 723–729why, one step back
723
724If you are concerned about the use of blocking IO, there are lots of projects725out there that combine Requests with one of Python's asynchronicity frameworks.726Two excellent examples are `grequests`_ and `requests-futures`_.727728.. _`grequests`: https://github.com/kennethreitz/grequests729.. _`requests-futures`: https://github.com/ross/requests-futures

Merge pull request #2176 from kevinburke/connectKenneth Reitzbefore adoption32e403a

lines 730–767why, one step back
730
731Timeouts732--------733734Most requests to external servers should have a timeout attached, in case the735server is not responding in a timely manner. Without a timeout, your code may736hang for minutes or more.737738The **connect** timeout is the number of seconds Requests will wait for your739client to establish a connection to a remote machine (corresponding to the740`connect()`_) call on the socket. It's a good practice to set connect timeouts741to slightly larger than a multiple of 3, which is the default `TCP packet742retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.743744Once your client has connected to the server and sent the HTTP request, the745**read** timeout is the number of seconds the client will wait for the server746to send a response. (Specifically, it's the number of seconds that the client747will wait *between* bytes sent from the server. In 99.9% of cases, this is the748time before the server sends the first byte).749750If you specify a single value for the timeout, like this::751752 r = requests.get('https://github.com', timeout=5)753754The timeout value will be applied to both the ``connect`` and the ``read``755timeouts. Specify a tuple if you would like to set the values separately::756757 r = requests.get('https://github.com', timeout=(3.05, 27))758759If the remote server is very slow, you can tell Requests to wait forever for760a response, by passing None as a timeout value and then retrieving a cup of761coffee.762763.. code-block:: python764765 r = requests.get('https://github.com', timeout=None)766767.. _`connect()`: http://linux.die.net/man/2/connect

Merge pull request #2203 from Lukasa/remove_certifiKenneth Reitzbefore adoption359659c

lines 768–785why, one step back
768
769CA Certificates770---------------771772By default Requests bundles a set of root CAs that it trusts, sourced from the773`Mozilla trust store`_. However, these are only updated once for each Requests774version. This means that if you pin a Requests version your certificates can775become extremely out of date.776777From Requests version 2.4.0 onwards, Requests will attempt to use certificates778from `certifi`_ if it is present on the system. This allows for users to update779their trusted certificates without having to change the code that runs on their780system.781782For the sake of security we recommend upgrading certifi frequently!783784.. _certifi: http://certifi.io/785.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt