Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

1,035 lines · 36.2 KiB

Last changed by

Merge pull request #4676 from jdufresne/doc-py3Nate Prewittbefore adoption16fd7e0

History of this file

Take it

1.. _advanced:23Advanced Usage4==============56.. image:: https://farm5.staticflickr.com/4263/35163665790_d182d84f5e_k_d.jpg78This document covers some of Requests more advanced features.910.. _session-objects:1112Session Objects13---------------1415The Session object allows you to persist certain parameters across16requests. It also persists cookies across all requests made from the17Session instance, and will use ``urllib3``'s `connection pooling`_. So if18you're making several requests to the same host, the underlying TCP19connection will be reused, which can result in a significant performance20increase (see `HTTP persistent connection`_).2122A Session object has all the methods of the main Requests API.2324Let's persist some cookies across requests::2526    s = requests.Session()2728    s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')29    r = s.get('http://httpbin.org/cookies')3031    print(r.text)32    # '{"cookies": {"sessioncookie": "123456789"}}'333435Sessions can also be used to provide default data to the request methods. This36is done by providing data to the properties on a Session object::3738    s = requests.Session()39    s.auth = ('user', 'pass')40    s.headers.update({'x-test': 'true'})4142    # both 'x-test' and 'x-test2' are sent43    s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})444546Any dictionaries that you pass to a request method will be merged with the47session-level values that are set. The method-level parameters override session48parameters.4950Note, however, that method-level parameters will *not* be persisted across51requests, even if using a session. This example will only send the cookies52with the first request, but not the second::5354    s = requests.Session()5556    r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})57    print(r.text)58    # '{"cookies": {"from-my": "browser"}}'5960    r = s.get('http://httpbin.org/cookies')61    print(r.text)62    # '{"cookies": {}}'636465If you want to manually add cookies to your session, use the66:ref:`Cookie utility functions <api-cookies>` to manipulate67:attr:`Session.cookies <requests.Session.cookies>`.6869Sessions can also be used as context managers::7071    with requests.Session() as s:72        s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')7374This will make sure the session is closed as soon as the ``with`` block is75exited, even if unhandled exceptions occurred.767778.. admonition:: Remove a Value From a Dict Parameter7980    Sometimes you'll want to omit session-level keys from a dict parameter. To81    do this, you simply set that key's value to ``None`` in the method-level82    parameter. It will automatically be omitted.8384All values that are contained within a session are directly available to you.85See the :ref:`Session API Docs <sessionapi>` to learn more.8687.. _request-and-response-objects:8889Request and Response Objects90----------------------------9192Whenever a call is made to ``requests.get()`` and friends, you are doing two93major things. First, you are constructing a ``Request`` object which will be94sent off to a server to request or query some resource. Second, a ``Response``95object is generated once Requests gets a response back from the server.96The ``Response`` object contains all of the information returned by the server and97also contains the ``Request`` object you created originally. Here is a simple98request to get some very important information from Wikipedia's servers::99100    >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')101102If we want to access the headers the server sent back to us, we do this::103104    >>> r.headers105    {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':106    'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':107    'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',108    'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',109    'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,110    must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':111    'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,112    MISS from cp1010.eqiad.wmnet:80'}113114However, if we want to get the headers we sent the server, we simply access the115request, and then the request's headers::116117    >>> r.request.headers118    {'Accept-Encoding': 'identity, deflate, compress, gzip',119    'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}120121.. _prepared-requests:122123Prepared Requests124-----------------125126Whenever you receive a :class:`Response <requests.Response>` object127from an API call or a Session call, the ``request`` attribute is actually the128``PreparedRequest`` that was used. In some cases you may wish to do some extra129work to the body or headers (or anything else really) before sending a130request. The simple recipe for this is the following::131132    from requests import Request, Session133134    s = Session()135136    req = Request('POST', url, data=data, headers=headers)137    prepped = req.prepare()138139    # do something with prepped.body140    prepped.body = 'No, I want exactly this as the body.'141142    # do something with prepped.headers143    del prepped.headers['Content-Type']144145    resp = s.send(prepped,146        stream=stream,147        verify=verify,148        proxies=proxies,149        cert=cert,150        timeout=timeout151    )152153    print(resp.status_code)154155Since you are not doing anything special with the ``Request`` object, you156prepare it immediately and modify the ``PreparedRequest`` object. You then157send that with the other parameters you would have sent to ``requests.*`` or158``Session.*``.159160However, the above code will lose some of the advantages of having a Requests161:class:`Session <requests.Session>` object. In particular,162:class:`Session <requests.Session>`-level state such as cookies will163not get applied to your request. To get a164:class:`PreparedRequest <requests.PreparedRequest>` with that state165applied, replace the call to :meth:`Request.prepare()166<requests.Request.prepare>` with a call to167:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::168169    from requests import Request, Session170171    s = Session()172    req = Request('GET',  url, data=data, headers=headers)173174    prepped = s.prepare_request(req)175176    # do something with prepped.body177    prepped.body = 'Seriously, send exactly these bytes.'178179    # do something with prepped.headers180    prepped.headers['Keep-Dead'] = 'parrot'181182    resp = s.send(prepped,183        stream=stream,184        verify=verify,185        proxies=proxies,186        cert=cert,187        timeout=timeout188    )189190    print(resp.status_code)191192When you are using the prepared request flow, keep in mind that it does not take into account the environment.193This can cause problems if you are using environment variables to change the behaviour of requests.194For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.195As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.196You can get around this behaviour by explicity merging the environment settings into your session::197198    from requests import Request, Session199200    s = Session()201    req = Request('GET', url)202203    prepped = s.prepare_request(req)204205    # Merge environment settings into session206    settings = s.merge_environment_settings(prepped.url, None, None, None, None)207    resp = s.send(prepped, **settings)208209    print(resp.status_code)210211.. _verification:212213SSL Cert Verification214---------------------215216Requests verifies SSL certificates for HTTPS requests, just like a web browser.217By default, SSL verification is enabled, and Requests will throw a SSLError if218it's unable to verify the certificate::219220    >>> requests.get('https://requestb.in')221    requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'222223I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::224225    >>> requests.get('https://github.com')226    <Response [200]>227228You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::229230    >>> requests.get('https://github.com', verify='/path/to/certfile')231232or persistent::233234    s = requests.Session()235    s.verify = '/path/to/certfile'236237.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using238  the c_rehash utility supplied with OpenSSL.239240This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.241242Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::243244    >>> requests.get('https://kennethreitz.org', verify=False)245    <Response [200]>246247By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.248249Client Side Certificates250------------------------251252You can also specify a local cert to use as client side certificate, as a single253file (containing the private key and the certificate) or as a tuple of both254files' paths::255256    >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))257    <Response [200]>258259or persistent::260261    s = requests.Session()262    s.cert = '/path/client.cert'263264If you specify a wrong path or an invalid cert, you'll get a SSLError::265266    >>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')267    SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib268269.. warning:: The private key to your local certificate *must* be unencrypted.270   Currently, Requests does not support using encrypted keys.271272.. _ca-certificates:273274CA Certificates275---------------276277Requests uses certificates from the package `certifi`_. This allows for users278to update their trusted certificates without changing the version of Requests.279280Before version 2.16, Requests bundled a set of root CAs that it trusted,281sourced from the `Mozilla trust store`_. The certificates were only updated282once for each Requests version. When ``certifi`` was not installed, this led to283extremely out-of-date certificate bundles when using significantly older284versions of Requests.285286For the sake of security we recommend upgrading certifi frequently!287288.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection289.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool290.. _certifi: https://certifiio.readthedocs.io/291.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt292293.. _body-content-workflow:294295Body Content Workflow296---------------------297298By default, when you make a request, the body of the response is downloaded299immediately. You can override this behaviour and defer downloading the response300body until you access the :attr:`Response.content <requests.Response.content>`301attribute with the ``stream`` parameter::302303    tarball_url = 'https://github.com/requests/requests/tarball/master'304    r = requests.get(tarball_url, stream=True)305306At this point only the response headers have been downloaded and the connection307remains open, hence allowing us to make content retrieval conditional::308309    if int(r.headers['content-length']) < TOO_LONG:310      content = r.content311      ...312313You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`314and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.315Alternatively, you can read the undecoded body from the underlying316urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at317:attr:`Response.raw <requests.Response.raw>`.318319If you set ``stream`` to ``True`` when making a request, Requests cannot320release the connection back to the pool unless you consume all the data or call321:meth:`Response.close <requests.Response.close>`. This can lead to322inefficiency with connections. If you find yourself partially reading request323bodies (or not reading them at all) while using ``stream=True``, you should324make the request within a ``with`` statement to ensure it's always closed::325326    with requests.get('http://httpbin.org/get', stream=True) as r:327        # Do things with the response here.328329.. _keep-alive:330331Keep-Alive332----------333334Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!335Any requests that you make within a session will automatically reuse the appropriate336connection!337338Note that connections are only released back to the pool for reuse once all body339data has been read; be sure to either set ``stream`` to ``False`` or read the340``content`` property of the ``Response`` object.341342.. _streaming-uploads:343344Streaming Uploads345-----------------346347Requests supports streaming uploads, which allow you to send large streams or348files without reading them into memory. To stream and upload, simply provide a349file-like object for your body::350351    with open('massive-body', 'rb') as f:352        requests.post('http://some.url/streamed', data=f)353354.. warning:: It is strongly recommended that you open files in `binary mode`_.355             This is because Requests may attempt to provide the356             ``Content-Length`` header for you, and if it does this value will357             be set to the number of *bytes* in the file. Errors may occur if358             you open the file in *text mode*.359360.. _binary mode: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files361362363.. _chunk-encoding:364365Chunk-Encoded Requests366----------------------367368Requests also supports Chunked transfer encoding for outgoing and incoming requests.369To send a chunk-encoded request, simply provide a generator (or any iterator without370a length) for your body::371372    def gen():373        yield 'hi'374        yield 'there'375376    requests.post('http://some.url/chunked', data=gen())377378For chunked encoded responses, it's best to iterate over the data using379:meth:`Response.iter_content() <requests.Response.iter_content>`. In380an ideal situation you'll have set ``stream=True`` on the request, in which381case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``382parameter of ``None``. If you want to set a maximum size of the chunk,383you can set a ``chunk_size`` parameter to any integer.384385386.. _multipart:387388POST Multiple Multipart-Encoded Files389-------------------------------------390391You can send multiple files in one request. For example, suppose you want to392upload image files to an HTML form with a multiple file field 'images'::393394    <input type="file" name="images" multiple="true" required="true"/>395396To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::397398    >>> url = 'http://httpbin.org/post'399    >>> multiple_files = [400            ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),401            ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]402    >>> r = requests.post(url, files=multiple_files)403    >>> r.text404    {405      ...406      'files': {'images': 'data:image/png;base64,iVBORw ....'}407      'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',408      ...409    }410411.. warning:: It is strongly recommended that you open files in `binary mode`_.412             This is because Requests may attempt to provide the413             ``Content-Length`` header for you, and if it does this value will414             be set to the number of *bytes* in the file. Errors may occur if415             you open the file in *text mode*.416417.. _binary mode: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files418419420.. _event-hooks:421422Event Hooks423-----------424425Requests has a hook system that you can use to manipulate portions of426the request process, or signal event handling.427428Available hooks:429430``response``:431    The response generated from a Request.432433434You can assign a hook function on a per-request basis by passing a435``{hook_name: callback_function}`` dictionary to the ``hooks`` request436parameter::437438    hooks={'response': print_url}439440That ``callback_function`` will receive a chunk of data as its first441argument.442443::444445    def print_url(r, *args, **kwargs):446        print(r.url)447448If an error occurs while executing your callback, a warning is given.449450If the callback function returns a value, it is assumed that it is to451replace the data that was passed in. If the function doesn't return452anything, nothing else is affected.453454::455456    def record_hook(r, *args, **kwargs):457        r.hook_called = True458        return r459460Let's print some request method arguments at runtime::461462    >>> requests.get('http://httpbin.org', hooks={'response': print_url})463    http://httpbin.org464    <Response [200]>465466You can add multiple hooks to a single request.  Let's call two hooks at once::467468    >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})469    >>> r.hook_called470    True471472You can also add hooks to a ``Session`` instance.  Any hooks you add will then473be called on every request made to the session.  For example::474475   >>> s = requests.Session()476   >>> s.hooks['response'].append(print_url)477   >>> s.get('http://httpbin.org')478    http://httpbin.org479    <Response [200]>480481A ``Session`` can have multiple hooks, which will be called in the order482they are added.483484.. _custom-auth:485486Custom Authentication487---------------------488489Requests allows you to use specify your own authentication mechanism.490491Any callable which is passed as the ``auth`` argument to a request method will492have the opportunity to modify the request before it is dispatched.493494Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,495and are easy to define. Requests provides two common authentication scheme496implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and497:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.498499Let's pretend that we have a web service that will only respond if the500``X-Pizza`` header is set to a password value. Unlikely, but just go with it.501502::503504    from requests.auth import AuthBase505506    class PizzaAuth(AuthBase):507        """Attaches HTTP Pizza Authentication to the given Request object."""508        def __init__(self, username):509            # setup any auth-related data here510            self.username = username511512        def __call__(self, r):513            # modify and return the request514            r.headers['X-Pizza'] = self.username515            return r516517Then, we can make a request using our Pizza Auth::518519    >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))520    <Response [200]>521522.. _streaming-requests:523524Streaming Requests525------------------526527With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily528iterate over streaming APIs such as the `Twitter Streaming529API <https://dev.twitter.com/streaming/overview>`_. Simply530set ``stream`` to ``True`` and iterate over the response with531:meth:`~requests.Response.iter_lines()`::532533    import json534    import requests535536    r = requests.get('http://httpbin.org/stream/20', stream=True)537538    for line in r.iter_lines():539540        # filter out keep-alive new lines541        if line:542            decoded_line = line.decode('utf-8')543            print(json.loads(decoded_line))544545When using `decode_unicode=True` with546:meth:`Response.iter_lines() <requests.Response.iter_lines>` or547:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want548to provide a fallback encoding in the event the server doesn't provide one::549550    r = requests.get('http://httpbin.org/stream/20', stream=True)551552    if r.encoding is None:553        r.encoding = 'utf-8'554555    for line in r.iter_lines(decode_unicode=True):556        if line:557            print(json.loads(line))558559.. warning::560561    :meth:`~requests.Response.iter_lines()` is not reentrant safe.562    Calling this method multiple times causes some of the received data563    being lost. In case you need to call it from multiple places, use564    the resulting iterator object instead::565566        lines = r.iter_lines()567        # Save the first line for later or just skip it568569        first_line = next(lines)570571        for line in lines:572            print(line)573574.. _proxies:575576Proxies577-------578579If you need to use a proxy, you can configure individual requests with the580``proxies`` argument to any request method::581582    import requests583584    proxies = {585      'http': 'http://10.10.1.10:3128',586      'https': 'http://10.10.1.10:1080',587    }588589    requests.get('http://example.org', proxies=proxies)590591You can also configure proxies by setting the environment variables592``HTTP_PROXY`` and ``HTTPS_PROXY``.593594::595596    $ export HTTP_PROXY="http://10.10.1.10:3128"597    $ export HTTPS_PROXY="http://10.10.1.10:1080"598599    $ python600    >>> import requests601    >>> requests.get('http://example.org')602603To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::604605    proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}606607To give a proxy for a specific scheme and host, use the608`scheme://hostname` form for the key.  This will match for609any request to the given scheme and exact hostname.610611::612613    proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}614615Note that proxy URLs must include the scheme.616617SOCKS618^^^^^619620.. versionadded:: 2.10.0621622In addition to basic HTTP proxies, Requests also supports proxies using the623SOCKS protocol. This is an optional feature that requires that additional624third-party libraries be installed before use.625626You can get the dependencies for this feature from ``pip``:627628.. code-block:: bash629630    $ pip install requests[socks]631632Once you've installed those dependencies, using a SOCKS proxy is just as easy633as using a HTTP one::634635    proxies = {636        'http': 'socks5://user:pass@host:port',637        'https': 'socks5://user:pass@host:port'638    }639640Using the scheme ``socks5`` causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use ``socks5h`` as the scheme.641642.. _compliance:643644Compliance645----------646647Requests is intended to be compliant with all relevant specifications and648RFCs where that compliance will not cause difficulties for users. This649attention to the specification can lead to some behaviour that may seem650unusual to those not familiar with the relevant specification.651652Encodings653^^^^^^^^^654655When you receive a response, Requests makes a guess at the encoding to656use for decoding the response when you access the :attr:`Response.text657<requests.Response.text>` attribute. Requests will first check for an658encoding in the HTTP header, and if none is present, will use `chardet659<https://pypi.org/project/chardet/>`_ to attempt to guess the encoding.660661The only time Requests will not do this is if no explicit charset662is present in the HTTP headers **and** the ``Content-Type``663header contains ``text``. In this situation, `RFC 2616664<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies665that the default charset must be ``ISO-8859-1``. Requests follows the666specification in this case. If you require a different encoding, you can667manually set the :attr:`Response.encoding <requests.Response.encoding>`668property, or use the raw :attr:`Response.content <requests.Response.content>`.669670.. _http-verbs:671672HTTP Verbs673----------674675Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,676HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of677using these various verbs in Requests, using the GitHub API.678679We will begin with the verb most commonly used: GET. HTTP GET is an idempotent680method that returns a resource from a given URL. As a result, it is the verb681you ought to use when attempting to retrieve data from a web location. An682example usage would be attempting to get information about a specific commit683from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it684like so::685686    >>> import requests687    >>> r = requests.get('https://api.github.com/repos/requests/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')688689We should confirm that GitHub responded correctly. If it has, we want to work690out what type of content it is. Do this like so::691692    >>> if r.status_code == requests.codes.ok:693    ...     print(r.headers['content-type'])694    ...695    application/json; charset=utf-8696697So, GitHub returns JSON. That's great, we can use the :meth:`r.json698<requests.Response.json>` method to parse it into Python objects.699700::701702    >>> commit_data = r.json()703704    >>> print(commit_data.keys())705    [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']706707    >>> print(commit_data[u'committer'])708    {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}709710    >>> print(commit_data[u'message'])711    makin' history712713So far, so simple. Well, let's investigate the GitHub API a little bit. Now,714we could look at the documentation, but we might have a little more fun if we715use Requests instead. We can take advantage of the Requests OPTIONS verb to716see what kinds of HTTP methods are supported on the url we just used.717718::719720    >>> verbs = requests.options(r.url)721    >>> verbs.status_code722    500723724Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't725actually implement the OPTIONS method. This is an annoying oversight, but it's726OK, we can just use the boring documentation. If GitHub had correctly727implemented OPTIONS, however, they should return the allowed methods in the728headers, e.g.729730::731732    >>> verbs = requests.options('http://a-good-website.com/api/cats')733    >>> print(verbs.headers['allow'])734    GET,HEAD,POST,OPTIONS735736Turning to the documentation, we see that the only other method allowed for737commits is POST, which creates a new commit. As we're using the Requests repo,738we should probably avoid making ham-handed POSTS to it. Instead, let's play739with the Issues feature of GitHub.740741This documentation was added in response to742`Issue #482 <https://github.com/requests/requests/issues/482>`_. Given that743this issue already exists, we will use it as an example. Let's start by getting it.744745::746747    >>> r = requests.get('https://api.github.com/repos/requests/requests/issues/482')748    >>> r.status_code749    200750751    >>> issue = json.loads(r.text)752753    >>> print(issue[u'title'])754    Feature any http verb in docs755756    >>> print(issue[u'comments'])757    3758759Cool, we have three comments. Let's take a look at the last of them.760761::762763    >>> r = requests.get(r.url + u'/comments')764    >>> r.status_code765    200766767    >>> comments = r.json()768769    >>> print(comments[0].keys())770    [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']771772    >>> print(comments[2][u'body'])773    Probably in the "advanced" section774775Well, that seems like a silly place. Let's post a comment telling the poster776that he's silly. Who is the poster, anyway?777778::779780    >>> print(comments[2][u'user'][u'login'])781    kennethreitz782783OK, so let's tell this Kenneth guy that we think this example should go in the784quickstart guide instead. According to the GitHub API doc, the way to do this785is to POST to the thread. Let's do it.786787::788789    >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})790    >>> url = u"https://api.github.com/repos/requests/requests/issues/482/comments"791792    >>> r = requests.post(url=url, data=body)793    >>> r.status_code794    404795796Huh, that's weird. We probably need to authenticate. That'll be a pain, right?797Wrong. Requests makes it easy to use many forms of authentication, including798the very common Basic Auth.799800::801802    >>> from requests.auth import HTTPBasicAuth803    >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')804805    >>> r = requests.post(url=url, data=body, auth=auth)806    >>> r.status_code807    201808809    >>> content = r.json()810    >>> print(content[u'body'])811    Sounds great! I'll get right on it.812813Brilliant. Oh, wait, no! I meant to add that it would take me a while, because814I had to go feed my cat. If only I could edit this comment! Happily, GitHub815allows us to use another HTTP verb, PATCH, to edit this comment. Let's do816that.817818::819820    >>> print(content[u"id"])821    5804413822823    >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})824    >>> url = u"https://api.github.com/repos/requests/requests/issues/comments/5804413"825826    >>> r = requests.patch(url=url, data=body, auth=auth)827    >>> r.status_code828    200829830Excellent. Now, just to torture this Kenneth guy, I've decided to let him831sweat and not tell him that I'm working on this. That means I want to delete832this comment. GitHub lets us delete comments using the incredibly aptly named833DELETE method. Let's get rid of it.834835::836837    >>> r = requests.delete(url=url, auth=auth)838    >>> r.status_code839    204840    >>> r.headers['status']841    '204 No Content'842843Excellent. All gone. The last thing I want to know is how much of my ratelimit844I've used. Let's find out. GitHub sends that information in the headers, so845rather than download the whole page I'll send a HEAD request to get the846headers.847848::849850    >>> r = requests.head(url=url, auth=auth)851    >>> print(r.headers)852    ...853    'x-ratelimit-remaining': '4995'854    'x-ratelimit-limit': '5000'855    ...856857Excellent. Time to write a Python program that abuses the GitHub API in all858kinds of exciting ways, 4995 more times.859860.. _custom-verbs:861862Custom Verbs863------------864865From time to time you may be working with a server that, for whatever reason,866allows use or even requires use of HTTP verbs not covered above. One example of867this would be the MKCOL method some WEBDAV servers use. Do not fret, these can868still be used with Requests. These make use of the built-in ``.request``869method. For example::870871    >>> r = requests.request('MKCOL', url, data=data)872    >>> r.status_code873    200 # Assuming your call was correct874875Utilising this, you can make use of any method verb that your server allows.876877878.. _link-headers:879880Link Headers881------------882883Many HTTP APIs feature Link headers. They make APIs more self describing and884discoverable.885886GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_887in their API, for example::888889    >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'890    >>> r = requests.head(url=url)891    >>> r.headers['link']892    '<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"'893894Requests will automatically parse these link headers and make them easily consumable::895896    >>> r.links["next"]897    {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}898899    >>> r.links["last"]900    {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}901902.. _transport-adapters:903904Transport Adapters905------------------906907As of v1.0.0, Requests has moved to a modular internal design. Part of the908reason this was done was to implement Transport Adapters, originally909`described here`_. Transport Adapters provide a mechanism to define interaction910methods for an HTTP service. In particular, they allow you to apply per-service911configuration.912913Requests ships with a single Transport Adapter, the :class:`HTTPAdapter914<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests915interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever916a Requests :class:`Session <requests.Session>` is initialized, one of these is917attached to the :class:`Session <requests.Session>` object for HTTP, and one918for HTTPS.919920Requests enables users to create and use their own Transport Adapters that921provide specific functionality. Once created, a Transport Adapter can be922mounted to a Session object, along with an indication of which web services923it should apply to.924925::926927    >>> s = requests.Session()928    >>> s.mount('http://www.github.com', MyAdapter())929930The mount call registers a specific instance of a Transport Adapter to a931prefix. Once mounted, any HTTP request made using that session whose URL starts932with the given prefix will use the given Transport Adapter.933934Many of the details of implementing a Transport Adapter are beyond the scope of935this documentation, but take a look at the next example for a simple SSL use-936case. For more than that, you might look at subclassing the937:class:`BaseAdapter <requests.adapters.BaseAdapter>`.938939Example: Specific SSL Version940^^^^^^^^^^^^^^^^^^^^^^^^^^^^^941942The Requests team has made a specific choice to use whatever SSL version is943default in the underlying library (`urllib3`_). Normally this is fine, but from944time to time, you might find yourself needing to connect to a service-endpoint945that uses a version that isn't compatible with the default.946947You can use Transport Adapters for this by taking most of the existing948implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets949passed-through to `urllib3`. We'll make a Transport Adapter that instructs the950library to use SSLv3::951952    import ssl953    from urllib3.poolmanager import PoolManager954955    from requests.adapters import HTTPAdapter956957958    class Ssl3HttpAdapter(HTTPAdapter):959        """"Transport adapter" that allows us to use SSLv3."""960961        def init_poolmanager(self, connections, maxsize, block=False):962            self.poolmanager = PoolManager(963                num_pools=connections, maxsize=maxsize,964                block=block, ssl_version=ssl.PROTOCOL_SSLv3)965966.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http967.. _`urllib3`: https://github.com/shazow/urllib3968969.. _blocking-or-nonblocking:970971Blocking Or Non-Blocking?972-------------------------973974With the default Transport Adapter in place, Requests does not provide any kind975of non-blocking IO. The :attr:`Response.content <requests.Response.content>`976property will block until the entire response has been downloaded. If977you require more granularity, the streaming features of the library (see978:ref:`streaming-requests`) allow you to retrieve smaller quantities of the979response at a time. However, these calls will still block.980981If you are concerned about the use of blocking IO, there are lots of projects982out there that combine Requests with one of Python's asynchronicity frameworks.983Some excellent examples are `requests-threads`_, `grequests`_,  and `requests-futures`_.984985.. _`requests-threads`: https://github.com/requests/requests-threads986.. _`grequests`: https://github.com/kennethreitz/grequests987.. _`requests-futures`: https://github.com/ross/requests-futures988989Header Ordering990---------------991992In 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.993994If 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.995996.. _timeouts:997998Timeouts999--------10001001Most requests to external servers should have a timeout attached, in case the1002server is not responding in a timely manner. By default, requests do not time1003out unless a timeout value is set explicitly. Without a timeout, your code may1004hang for minutes or more.10051006The **connect** timeout is the number of seconds Requests will wait for your1007client to establish a connection to a remote machine (corresponding to the1008`connect()`_) call on the socket. It's a good practice to set connect timeouts1009to slightly larger than a multiple of 3, which is the default `TCP packet1010retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.10111012Once your client has connected to the server and sent the HTTP request, the1013**read** timeout is the number of seconds the client will wait for the server1014to send a response. (Specifically, it's the number of seconds that the client1015will wait *between* bytes sent from the server. In 99.9% of cases, this is the1016time before the server sends the first byte).10171018If you specify a single value for the timeout, like this::10191020    r = requests.get('https://github.com', timeout=5)10211022The timeout value will be applied to both the ``connect`` and the ``read``1023timeouts. Specify a tuple if you would like to set the values separately::10241025    r = requests.get('https://github.com', timeout=(3.05, 27))10261027If the remote server is very slow, you can tell Requests to wait forever for1028a response, by passing None as a timeout value and then retrieving a cup of1029coffee.10301031::10321033    r = requests.get('https://github.com', timeout=None)10341035.. _`connect()`: http://linux.die.net/man/2/connect