advanced.rst
This file
Path
docs/user/advanced.rst
989 lines · 34.4 KiB
Last changed by
Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptionb60c5a5
History of this fileTake it
1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.78.. _session-objects:910Session Objects11---------------1213The Session object allows you to persist certain parameters across14requests. It also persists cookies across all requests made from the15Session instance, and will use ``urllib3``'s `connection pooling`_. So if16you're making several requests to the same host, the underlying TCP17connection will be reused, which can result in a significant performance18increase (see `HTTP persistent connection`_).1920A Session object has all the methods of the main Requests API.2122Let's persist some cookies across requests::2324 s = requests.Session()2526 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')27 r = s.get('http://httpbin.org/cookies')2829 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'313233Sessions can also be used to provide default data to the request methods. This34is done by providing data to the properties on a Session object::3536 s = requests.Session()37 s.auth = ('user', 'pass')38 s.headers.update({'x-test': 'true'})3940 # both 'x-test' and 'x-test2' are sent41 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})424344Any dictionaries that you pass to a request method will be merged with the45session-level values that are set. The method-level parameters override session46parameters.4748Note, however, that method-level parameters will *not* be persisted across49requests, even if using a session. This example will only send the cookies50with the first request, but not the second::5152 s = requests.Session()5354 r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'5758 r = s.get('http://httpbin.org/cookies')59 print(r.text)60 # '{"cookies": {}}'616263If you want to manually add cookies to your session, use the64:ref:`Cookie utility functions <api-cookies>` to manipulate65:attr:`Session.cookies <requests.Session.cookies>`.6667Sessions can also be used as context managers::6869 with requests.Session() as s:70 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')7172This will make sure the session is closed as soon as the ``with`` block is73exited, even if unhandled exceptions occurred.747576.. admonition:: Remove a Value From a Dict Parameter7778 Sometimes you'll want to omit session-level keys from a dict parameter. To79 do this, you simply set that key's value to ``None`` in the method-level80 parameter. It will automatically be omitted.8182All values that are contained within a session are directly available to you.83See the :ref:`Session API Docs <sessionapi>` to learn more.8485.. _request-and-response-objects:8687Request and Response Objects88----------------------------8990Whenever a call is made to ``requests.get()`` and friends, you are doing two91major things. First, you are constructing a ``Request`` object which will be92sent off to a server to request or query some resource. Second, a ``Response``93object is generated once Requests gets a response back from the server.94The ``Response`` object contains all of the information returned by the server and95also contains the ``Request`` object you created originally. Here is a simple96request to get some very important information from Wikipedia's servers::9798 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')99100If we want to access the headers the server sent back to us, we do this::101102 >>> r.headers103 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':104 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':105 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',106 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',107 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,108 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':109 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,110 MISS from cp1010.eqiad.wmnet:80'}111112However, if we want to get the headers we sent the server, we simply access the113request, and then the request's headers::114115 >>> r.request.headers116 {'Accept-Encoding': 'identity, deflate, compress, gzip',117 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}118119.. _prepared-requests:120121Prepared Requests122-----------------123124Whenever you receive a :class:`Response <requests.Response>` object125from an API call or a Session call, the ``request`` attribute is actually the126``PreparedRequest`` that was used. In some cases you may wish to do some extra127work to the body or headers (or anything else really) before sending a128request. The simple recipe for this is the following::129130 from requests import Request, Session131132 s = Session()133134 req = Request('POST', url, data=data, headers=headers)135 prepped = req.prepare()136137 # do something with prepped.body138 prepped.body = 'No, I want exactly this as the body.'139140 # do something with prepped.headers141 del prepped.headers['Content-Type']142143 resp = s.send(prepped,144 stream=stream,145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150151 print(resp.status_code)152153Since you are not doing anything special with the ``Request`` object, you154prepare it immediately and modify the ``PreparedRequest`` object. You then155send that with the other parameters you would have sent to ``requests.*`` or156``Session.*``.157158However, the above code will lose some of the advantages of having a Requests159:class:`Session <requests.Session>` object. In particular,160:class:`Session <requests.Session>`-level state such as cookies will161not get applied to your request. To get a162:class:`PreparedRequest <requests.PreparedRequest>` with that state163applied, replace the call to :meth:`Request.prepare()164<requests.Request.prepare>` with a call to165:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::166167 from requests import Request, Session168169 s = Session()170 req = Request('GET', url, data=data, headers=headers)171172 prepped = s.prepare_request(req)173174 # do something with prepped.body175 prepped.body = 'Seriously, send exactly these bytes.'176177 # do something with prepped.headers178 prepped.headers['Keep-Dead'] = 'parrot'179180 resp = s.send(prepped,181 stream=stream,182 verify=verify,183 proxies=proxies,184 cert=cert,185 timeout=timeout186 )187188 print(resp.status_code)189190.. _verification:191192SSL Cert Verification193---------------------194195Requests verifies SSL certificates for HTTPS requests, just like a web browser.196By default, SSL verification is enabled, and Requests will throw a SSLError if197it's unable to verify the certificate::198199 >>> requests.get('https://requestb.in')200 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'201202I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::203204 >>> requests.get('https://github.com')205 <Response [200]>206207You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::208209 >>> requests.get('https://github.com', verify='/path/to/certfile')210211or persistent::212213 s = requests.Session()214 s.verify = '/path/to/certfile'215216.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using217 the c_rehash utility supplied with OpenSSL.218219This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.220221Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::222223 >>> requests.get('https://kennethreitz.org', verify=False)224 <Response [200]>225226By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.227228You can also specify a local cert to use as client side certificate, as a single229file (containing the private key and the certificate) or as a tuple of both230files' paths::231232 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))233 <Response [200]>234235or persistent::236237 s = requests.Session()238 s.cert = '/path/client.cert'239240If you specify a wrong path or an invalid cert, you'll get a SSLError::241242 >>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')243 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib244245.. warning:: The private key to your local certificate *must* be unencrypted.246 Currently, Requests does not support using encrypted keys.247248.. _ca-certificates:249250CA Certificates251---------------252253By default, Requests bundles a set of root CAs that it trusts, sourced from the254`Mozilla trust store`_. However, these are only updated once for each Requests255version. This means that if you pin a Requests version your certificates can256become extremely out of date.257258From Requests version 2.4.0 onwards, Requests will attempt to use certificates259from `certifi`_ if it is present on the system. This allows for users to update260their trusted certificates without having to change the code that runs on their261system.262263For the sake of security we recommend upgrading certifi frequently!264265.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection266.. _connection pooling: http://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool267.. _certifi: http://certifi.io/268.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt269270.. _body-content-workflow:271272Body Content Workflow273---------------------274275By default, when you make a request, the body of the response is downloaded276immediately. You can override this behaviour and defer downloading the response277body until you access the :attr:`Response.content <requests.Response.content>`278attribute with the ``stream`` parameter::279280 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'281 r = requests.get(tarball_url, stream=True)282283At this point only the response headers have been downloaded and the connection284remains open, hence allowing us to make content retrieval conditional::285286 if int(r.headers['content-length']) < TOO_LONG:287 content = r.content288 ...289290You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`291and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.292Alternatively, you can read the undecoded body from the underlying293urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at294:attr:`Response.raw <requests.Response.raw>`.295296If you set ``stream`` to ``True`` when making a request, Requests cannot297release the connection back to the pool unless you consume all the data or call298:meth:`Response.close <requests.Response.close>`. This can lead to299inefficiency with connections. If you find yourself partially reading request300bodies (or not reading them at all) while using ``stream=True``, you should301consider using ``contextlib.closing`` (`documented here`_), like this::302303 from contextlib import closing304305 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:306 # Do things with the response here.307308.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing309310.. _keep-alive:311312Keep-Alive313----------314315Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!316Any requests that you make within a session will automatically reuse the appropriate317connection!318319Note that connections are only released back to the pool for reuse once all body320data has been read; be sure to either set ``stream`` to ``False`` or read the321``content`` property of the ``Response`` object.322323.. _streaming-uploads:324325Streaming Uploads326-----------------327328Requests supports streaming uploads, which allow you to send large streams or329files without reading them into memory. To stream and upload, simply provide a330file-like object for your body::331332 with open('massive-body', 'rb') as f:333 requests.post('http://some.url/streamed', data=f)334335.. warning:: It is strongly recommended that you open files in `binary mode`_.336 This is because Requests may attempt to provide the337 ``Content-Length`` header for you, and if it does this value will338 be set to the number of *bytes* in the file. Errors may occur if339 you open the file in *text mode*.340341.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files342343344.. _chunk-encoding:345346Chunk-Encoded Requests347----------------------348349Requests also supports Chunked transfer encoding for outgoing and incoming requests.350To send a chunk-encoded request, simply provide a generator (or any iterator without351a length) for your body::352353 def gen():354 yield 'hi'355 yield 'there'356357 requests.post('http://some.url/chunked', data=gen())358359For chunked encoded responses, it's best to iterate over the data using360:meth:`Response.iter_content() <requests.Response.iter_content>`. In361an ideal situation you'll have set ``stream=True`` on the request, in which362case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``363parameter of ``None``. If you want to set a maximum size of the chunk,364you can set a ``chunk_size`` parameter to any integer.365366367.. _multipart:368369POST Multiple Multipart-Encoded Files370-------------------------------------371372You can send multiple files in one request. For example, suppose you want to373upload image files to an HTML form with a multiple file field 'images'::374375 <input type="file" name="images" multiple="true" required="true"/>376377To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::378379 >>> url = 'http://httpbin.org/post'380 >>> multiple_files = [381 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),382 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]383 >>> r = requests.post(url, files=multiple_files)384 >>> r.text385 {386 ...387 'files': {'images': 'data:image/png;base64,iVBORw ....'}388 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',389 ...390 }391392.. warning:: It is strongly recommended that you open files in `binary mode`_.393 This is because Requests may attempt to provide the394 ``Content-Length`` header for you, and if it does this value will395 be set to the number of *bytes* in the file. Errors may occur if396 you open the file in *text mode*.397398.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files399400401.. _event-hooks:402403Event Hooks404-----------405406Requests has a hook system that you can use to manipulate portions of407the request process, or signal event handling.408409Available hooks:410411``response``:412 The response generated from a Request.413414415You can assign a hook function on a per-request basis by passing a416``{hook_name: callback_function}`` dictionary to the ``hooks`` request417parameter::418419 hooks=dict(response=print_url)420421That ``callback_function`` will receive a chunk of data as its first422argument.423424::425426 def print_url(r, *args, **kwargs):427 print(r.url)428429If an error occurs while executing your callback, a warning is given.430431If the callback function returns a value, it is assumed that it is to432replace the data that was passed in. If the function doesn't return433anything, nothing else is effected.434435Let's print some request method arguments at runtime::436437 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))438 http://httpbin.org439 <Response [200]>440441.. _custom-auth:442443Custom Authentication444---------------------445446Requests allows you to use specify your own authentication mechanism.447448Any callable which is passed as the ``auth`` argument to a request method will449have the opportunity to modify the request before it is dispatched.450451Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,452and are easy to define. Requests provides two common authentication scheme453implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and454:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.455456Let's pretend that we have a web service that will only respond if the457``X-Pizza`` header is set to a password value. Unlikely, but just go with it.458459::460461 from requests.auth import AuthBase462463 class PizzaAuth(AuthBase):464 """Attaches HTTP Pizza Authentication to the given Request object."""465 def __init__(self, username):466 # setup any auth-related data here467 self.username = username468469 def __call__(self, r):470 # modify and return the request471 r.headers['X-Pizza'] = self.username472 return r473474Then, we can make a request using our Pizza Auth::475476 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))477 <Response [200]>478479.. _streaming-requests:480481Streaming Requests482------------------483484With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily485iterate over streaming APIs such as the `Twitter Streaming486API <https://dev.twitter.com/streaming/overview>`_. Simply487set ``stream`` to ``True`` and iterate over the response with488:meth:`~requests.Response.iter_lines()`::489490 import json491 import requests492493 r = requests.get('http://httpbin.org/stream/20', stream=True)494495 for line in r.iter_lines():496497 # filter out keep-alive new lines498 if line:499 decoded_line = line.decode('utf-8')500 print(json.loads(decoded_line))501502When using `decode_unicode=True` with503:meth:`Response.iter_lines() <requests.Response.iter_lines>` or504:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want505to provide a fallback encoding in the event the server doesn't provide one::506507 r = requests.get('http://httpbin.org/stream/20', stream=True)508509 if r.encoding is None:510 r.encoding = 'utf-8'511512 for line in r.iter_lines(decode_unicode=True):513 if line:514 print(json.loads(line))515516.. warning::517518 :meth:`~requests.Response.iter_lines()` is not reentrant safe.519 Calling this method multiple times causes some of the received data520 being lost. In case you need to call it from multiple places, use521 the resulting iterator object instead::522523 lines = r.iter_lines()524 # Save the first line for later or just skip it525526 first_line = next(lines)527528 for line in lines:529 print(line)530531.. _proxies:532533Proxies534-------535536If you need to use a proxy, you can configure individual requests with the537``proxies`` argument to any request method::538539 import requests540541 proxies = {542 'http': 'http://10.10.1.10:3128',543 'https': 'http://10.10.1.10:1080',544 }545546 requests.get('http://example.org', proxies=proxies)547548You can also configure proxies by setting the environment variables549``HTTP_PROXY`` and ``HTTPS_PROXY``.550551::552553 $ export HTTP_PROXY="http://10.10.1.10:3128"554 $ export HTTPS_PROXY="http://10.10.1.10:1080"555556 $ python557 >>> import requests558 >>> requests.get('http://example.org')559560To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::561562 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}563564To give a proxy for a specific scheme and host, use the565`scheme://hostname` form for the key. This will match for566any request to the given scheme and exact hostname.567568::569570 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}571572Note that proxy URLs must include the scheme.573574SOCKS575^^^^^576577.. versionadded:: 2.10.0578579In addition to basic HTTP proxies, Requests also supports proxies using the580SOCKS protocol. This is an optional feature that requires that additional581third-party libraries be installed before use.582583You can get the dependencies for this feature from ``pip``:584585.. code-block:: bash586587 $ pip install requests[socks]588589Once you've installed those dependencies, using a SOCKS proxy is just as easy590as using a HTTP one::591592 proxies = {593 'http': 'socks5://user:pass@host:port',594 'https': 'socks5://user:pass@host:port'595 }596597.. _compliance:598599Compliance600----------601602Requests is intended to be compliant with all relevant specifications and603RFCs where that compliance will not cause difficulties for users. This604attention to the specification can lead to some behaviour that may seem605unusual to those not familiar with the relevant specification.606607Encodings608^^^^^^^^^609610When you receive a response, Requests makes a guess at the encoding to611use for decoding the response when you access the :attr:`Response.text612<requests.Response.text>` attribute. Requests will first check for an613encoding in the HTTP header, and if none is present, will use `chardet614<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.615616The only time Requests will not do this is if no explicit charset617is present in the HTTP headers **and** the ``Content-Type``618header contains ``text``. In this situation, `RFC 2616619<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies620that the default charset must be ``ISO-8859-1``. Requests follows the621specification in this case. If you require a different encoding, you can622manually set the :attr:`Response.encoding <requests.Response.encoding>`623property, or use the raw :attr:`Response.content <requests.Response.content>`.624625.. _http-verbs:626627HTTP Verbs628----------629630Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,631HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of632using these various verbs in Requests, using the GitHub API.633634We will begin with the verb most commonly used: GET. HTTP GET is an idempotent635method that returns a resource from a given URL. As a result, it is the verb636you ought to use when attempting to retrieve data from a web location. An637example usage would be attempting to get information about a specific commit638from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it639like so::640641 >>> import requests642 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')643644We should confirm that GitHub responded correctly. If it has, we want to work645out what type of content it is. Do this like so::646647 >>> if r.status_code == requests.codes.ok:648 ... print(r.headers['content-type'])649 ...650 application/json; charset=utf-8651652So, GitHub returns JSON. That's great, we can use the :meth:`r.json653<requests.Response.json>` method to parse it into Python objects.654655::656657 >>> commit_data = r.json()658659 >>> print(commit_data.keys())660 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']661662 >>> print(commit_data[u'committer'])663 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}664665 >>> print(commit_data[u'message'])666 makin' history667668So far, so simple. Well, let's investigate the GitHub API a little bit. Now,669we could look at the documentation, but we might have a little more fun if we670use Requests instead. We can take advantage of the Requests OPTIONS verb to671see what kinds of HTTP methods are supported on the url we just used.672673::674675 >>> verbs = requests.options(r.url)676 >>> verbs.status_code677 500678679Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't680actually implement the OPTIONS method. This is an annoying oversight, but it's681OK, we can just use the boring documentation. If GitHub had correctly682implemented OPTIONS, however, they should return the allowed methods in the683headers, e.g.684685::686687 >>> verbs = requests.options('http://a-good-website.com/api/cats')688 >>> print(verbs.headers['allow'])689 GET,HEAD,POST,OPTIONS690691Turning to the documentation, we see that the only other method allowed for692commits is POST, which creates a new commit. As we're using the Requests repo,693we should probably avoid making ham-handed POSTS to it. Instead, let's play694with the Issues feature of GitHub.695696This documentation was added in response to697`Issue #482 <https://github.com/kennethreitz/requests/issues/482>`_. Given that698this issue already exists, we will use it as an example. Let's start by getting it.699700::701702 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')703 >>> r.status_code704 200705706 >>> issue = json.loads(r.text)707708 >>> print(issue[u'title'])709 Feature any http verb in docs710711 >>> print(issue[u'comments'])712 3713714Cool, we have three comments. Let's take a look at the last of them.715716::717718 >>> r = requests.get(r.url + u'/comments')719 >>> r.status_code720 200721722 >>> comments = r.json()723724 >>> print(comments[0].keys())725 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']726727 >>> print(comments[2][u'body'])728 Probably in the "advanced" section729730Well, that seems like a silly place. Let's post a comment telling the poster731that he's silly. Who is the poster, anyway?732733::734735 >>> print(comments[2][u'user'][u'login'])736 kennethreitz737738OK, so let's tell this Kenneth guy that we think this example should go in the739quickstart guide instead. According to the GitHub API doc, the way to do this740is to POST to the thread. Let's do it.741742::743744 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})745 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"746747 >>> r = requests.post(url=url, data=body)748 >>> r.status_code749 404750751Huh, that's weird. We probably need to authenticate. That'll be a pain, right?752Wrong. Requests makes it easy to use many forms of authentication, including753the very common Basic Auth.754755::756757 >>> from requests.auth import HTTPBasicAuth758 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')759760 >>> r = requests.post(url=url, data=body, auth=auth)761 >>> r.status_code762 201763764 >>> content = r.json()765 >>> print(content[u'body'])766 Sounds great! I'll get right on it.767768Brilliant. Oh, wait, no! I meant to add that it would take me a while, because769I had to go feed my cat. If only I could edit this comment! Happily, GitHub770allows us to use another HTTP verb, PATCH, to edit this comment. Let's do771that.772773::774775 >>> print(content[u"id"])776 5804413777778 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})779 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"780781 >>> r = requests.patch(url=url, data=body, auth=auth)782 >>> r.status_code783 200784785Excellent. Now, just to torture this Kenneth guy, I've decided to let him786sweat and not tell him that I'm working on this. That means I want to delete787this comment. GitHub lets us delete comments using the incredibly aptly named788DELETE method. Let's get rid of it.789790::791792 >>> r = requests.delete(url=url, auth=auth)793 >>> r.status_code794 204795 >>> r.headers['status']796 '204 No Content'797798Excellent. All gone. The last thing I want to know is how much of my ratelimit799I've used. Let's find out. GitHub sends that information in the headers, so800rather than download the whole page I'll send a HEAD request to get the801headers.802803::804805 >>> r = requests.head(url=url, auth=auth)806 >>> print(r.headers)807 ...808 'x-ratelimit-remaining': '4995'809 'x-ratelimit-limit': '5000'810 ...811812Excellent. Time to write a Python program that abuses the GitHub API in all813kinds of exciting ways, 4995 more times.814815.. _custom-verbs:816817Custom Verbs818------------819820From time to time you may be working with a server that, for whatever reason,821allows use or even requires use of HTTP verbs not covered above. One example of822this would be the MKCOL method some WEBDAV servers use. Do not fret, these can823still be used with Requests. These make use of the built-in ``.request``824method. For example::825826 >>> r = requests.request('MKCOL', url, data=data)827 >>> r.status_code828 200 # Assuming your call was correct829830Utilising this, you can make use of any method verb that your server allows.831832833.. _link-headers:834835Link Headers836------------837838Many HTTP APIs feature Link headers. They make APIs more self describing and839discoverable.840841GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_842in their API, for example::843844 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'845 >>> r = requests.head(url=url)846 >>> r.headers['link']847 '<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"'848849Requests will automatically parse these link headers and make them easily consumable::850851 >>> r.links["next"]852 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}853854 >>> r.links["last"]855 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}856857.. _transport-adapters:858859Transport Adapters860------------------861862As of v1.0.0, Requests has moved to a modular internal design. Part of the863reason this was done was to implement Transport Adapters, originally864`described here`_. Transport Adapters provide a mechanism to define interaction865methods for an HTTP service. In particular, they allow you to apply per-service866configuration.867868Requests ships with a single Transport Adapter, the :class:`HTTPAdapter869<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests870interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever871a Requests :class:`Session <requests.Session>` is initialized, one of these is872attached to the :class:`Session <requests.Session>` object for HTTP, and one873for HTTPS.874875Requests enables users to create and use their own Transport Adapters that876provide specific functionality. Once created, a Transport Adapter can be877mounted to a Session object, along with an indication of which web services878it should apply to.879880::881882 >>> s = requests.Session()883 >>> s.mount('http://www.github.com', MyAdapter())884885The mount call registers a specific instance of a Transport Adapter to a886prefix. Once mounted, any HTTP request made using that session whose URL starts887with the given prefix will use the given Transport Adapter.888889Many of the details of implementing a Transport Adapter are beyond the scope of890this documentation, but take a look at the next example for a simple SSL use-891case. For more than that, you might look at subclassing the892:class:`BaseAdapter <requests.adapters.BaseAdapter>`.893894Example: Specific SSL Version895^^^^^^^^^^^^^^^^^^^^^^^^^^^^^896897The Requests team has made a specific choice to use whatever SSL version is898default in the underlying library (`urllib3`_). Normally this is fine, but from899time to time, you might find yourself needing to connect to a service-endpoint900that uses a version that isn't compatible with the default.901902You can use Transport Adapters for this by taking most of the existing903implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets904passed-through to `urllib3`. We'll make a Transport Adapter that instructs the905library to use SSLv3::906907 import ssl908909 from requests.adapters import HTTPAdapter910 from requests.packages.urllib3.poolmanager import PoolManager911912913 class Ssl3HttpAdapter(HTTPAdapter):914 """"Transport adapter" that allows us to use SSLv3."""915916 def init_poolmanager(self, connections, maxsize, block=False):917 self.poolmanager = PoolManager(918 num_pools=connections, maxsize=maxsize,919 block=block, ssl_version=ssl.PROTOCOL_SSLv3)920921.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http922.. _`urllib3`: https://github.com/shazow/urllib3923924.. _blocking-or-nonblocking:925926Blocking Or Non-Blocking?927-------------------------928929With the default Transport Adapter in place, Requests does not provide any kind930of non-blocking IO. The :attr:`Response.content <requests.Response.content>`931property will block until the entire response has been downloaded. If932you require more granularity, the streaming features of the library (see933:ref:`streaming-requests`) allow you to retrieve smaller quantities of the934response at a time. However, these calls will still block.935936If you are concerned about the use of blocking IO, there are lots of projects937out there that combine Requests with one of Python's asynchronicity frameworks.938Two excellent examples are `grequests`_ and `requests-futures`_.939940.. _`grequests`: https://github.com/kennethreitz/grequests941.. _`requests-futures`: https://github.com/ross/requests-futures942943Header Ordering944---------------945946In unusual circumstances you may want to provide headers in an ordered manner. If you pass an ``OrderedDict`` to the ``headers`` keyword argument, that will provide the headers with an ordering. *However*, the ordering of the default headers used by Requests will be preferred, which means that if you override default headers in the ``headers`` keyword argument, they may appear out of order compared to other headers in that keyword argument.947948If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.949950.. _timeouts:951952Timeouts953--------954955Most requests to external servers should have a timeout attached, in case the956server is not responding in a timely manner. By default, requests do not time957out unless a timeout value is set explicitly. Without a timeout, your code may958hang for minutes or more.959960The **connect** timeout is the number of seconds Requests will wait for your961client to establish a connection to a remote machine (corresponding to the962`connect()`_) call on the socket. It's a good practice to set connect timeouts963to slightly larger than a multiple of 3, which is the default `TCP packet964retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.965966Once your client has connected to the server and sent the HTTP request, the967**read** timeout is the number of seconds the client will wait for the server968to send a response. (Specifically, it's the number of seconds that the client969will wait *between* bytes sent from the server. In 99.9% of cases, this is the970time before the server sends the first byte).971972If you specify a single value for the timeout, like this::973974 r = requests.get('https://github.com', timeout=5)975976The timeout value will be applied to both the ``connect`` and the ``read``977timeouts. Specify a tuple if you would like to set the values separately::978979 r = requests.get('https://github.com', timeout=(3.05, 27))980981If the remote server is very slow, you can tell Requests to wait forever for982a response, by passing None as a timeout value and then retrieving a cup of983coffee.984985::986987 r = requests.get('https://github.com', timeout=None)988989.. _`connect()`: http://linux.die.net/man/2/connect