advanced.rst
This file
Path
docs/user/advanced.rst
940 lines · 32.2 KiB
Last changed by
Merge pull request #3173 from Lukasa/socks-proxy-docsIan Cordascobefore adoption3669b42
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')210211.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using 212 the c_rehash utility supplied with OpenSSL.213214This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.215216Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.217218::219220 >>> requests.get('https://kennethreitz.com', verify=False)221 <Response [200]>222223By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.224225You can also specify a local cert to use as client side certificate, as a single226file (containing the private key and the certificate) or as a tuple of both227file's path::228229 >>> requests.get('https://kennethreitz.com', cert=('/path/client.cert', '/path/client.key'))230 <Response [200]>231232If you specify a wrong path or an invalid cert, you'll get a SSLError::233234 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/client.pem')235 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib236237.. warning:: The private key to your local certificate *must* be unencrypted.238 Currently, requests does not support using encrypted keys.239240.. _ca-certificates:241242CA Certificates243---------------244245By default Requests bundles a set of root CAs that it trusts, sourced from the246`Mozilla trust store`_. However, these are only updated once for each Requests247version. This means that if you pin a Requests version your certificates can248become extremely out of date.249250From Requests version 2.4.0 onwards, Requests will attempt to use certificates251from `certifi`_ if it is present on the system. This allows for users to update252their trusted certificates without having to change the code that runs on their253system.254255For the sake of security we recommend upgrading certifi frequently!256257.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection258.. _connection pooling: https://urllib3.readthedocs.io/en/latest/pools.html259.. _certifi: http://certifi.io/260.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt261262.. _body-content-workflow:263264Body Content Workflow265---------------------266267By default, when you make a request, the body of the response is downloaded268immediately. You can override this behaviour and defer downloading the response269body until you access the :class:`Response.content <requests.Response.content>`270attribute with the ``stream`` parameter::271272 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'273 r = requests.get(tarball_url, stream=True)274275At this point only the response headers have been downloaded and the connection276remains open, hence allowing us to make content retrieval conditional::277278 if int(r.headers['content-length']) < TOO_LONG:279 content = r.content280 ...281282You can further control the workflow by use of the :class:`Response.iter_content <requests.Response.iter_content>`283and :class:`Response.iter_lines <requests.Response.iter_lines>` methods.284Alternatively, you can read the undecoded body from the underlying285urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at286:class:`Response.raw <requests.Response.raw>`.287288If you set ``stream`` to ``True`` when making a request, Requests cannot289release the connection back to the pool unless you consume all the data or call290:class:`Response.close <requests.Response.close>`. This can lead to291inefficiency with connections. If you find yourself partially reading request292bodies (or not reading them at all) while using ``stream=True``, you should293consider using ``contextlib.closing`` (`documented here`_), like this::294295 from contextlib import closing296297 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:298 # Do things with the response here.299300.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing301302.. _keep-alive:303304Keep-Alive305----------306307Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!308Any requests that you make within a session will automatically reuse the appropriate309connection!310311Note that connections are only released back to the pool for reuse once all body312data has been read; be sure to either set ``stream`` to ``False`` or read the313``content`` property of the ``Response`` object.314315.. _streaming-uploads:316317Streaming Uploads318-----------------319320Requests supports streaming uploads, which allow you to send large streams or321files without reading them into memory. To stream and upload, simply provide a322file-like object for your body::323324 with open('massive-body', 'rb') as f:325 requests.post('http://some.url/streamed', data=f)326327.. warning:: It is strongly recommended that you open files in `binary mode`_.328 This is because Requests may attempt to provide the329 ``Content-Length`` header for you, and if it does this value will330 be set to the number of *bytes* in the file. Errors may occur if331 you open the file in *text mode*.332333.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files334335336.. _chunk-encoding:337338Chunk-Encoded Requests339----------------------340341Requests also supports Chunked transfer encoding for outgoing and incoming requests.342To send a chunk-encoded request, simply provide a generator (or any iterator without343a length) for your body::344345 def gen():346 yield 'hi'347 yield 'there'348349 requests.post('http://some.url/chunked', data=gen())350351For chunked encoded responses, it's best to iterate over the data using352:meth:`Response.iter_content() <requests.models.Response.iter_content>`. In353an ideal situation you'll have set ``stream=True`` on the request, in which354case you can iterate chunk-by-chunk by calling ``iter_content`` with a chunk355size parameter of ``None``. If you want to set a maximum size of the chunk,356you can set a chunk size parameter to any integer.357358359.. _multipart:360361POST Multiple Multipart-Encoded Files362-------------------------------------363364You can send multiple files in one request. For example, suppose you want to365upload image files to an HTML form with a multiple file field 'images'::366367 <input type="file" name="images" multiple="true" required="true"/>368369To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::370371 >>> url = 'http://httpbin.org/post'372 >>> multiple_files = [373 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),374 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]375 >>> r = requests.post(url, files=multiple_files)376 >>> r.text377 {378 ...379 'files': {'images': 'data:image/png;base64,iVBORw ....'}380 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',381 ...382 }383384.. warning:: It is strongly recommended that you open files in `binary mode`_.385 This is because Requests may attempt to provide the386 ``Content-Length`` header for you, and if it does this value will387 be set to the number of *bytes* in the file. Errors may occur if388 you open the file in *text mode*.389390.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files391392393.. _event-hooks:394395Event Hooks396-----------397398Requests has a hook system that you can use to manipulate portions of399the request process, or signal event handling.400401Available hooks:402403``response``:404 The response generated from a Request.405406407You can assign a hook function on a per-request basis by passing a408``{hook_name: callback_function}`` dictionary to the ``hooks`` request409parameter::410411 hooks=dict(response=print_url)412413That ``callback_function`` will receive a chunk of data as its first414argument.415416::417418 def print_url(r, *args, **kwargs):419 print(r.url)420421If an error occurs while executing your callback, a warning is given.422423If the callback function returns a value, it is assumed that it is to424replace the data that was passed in. If the function doesn't return425anything, nothing else is effected.426427Let's print some request method arguments at runtime::428429 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))430 http://httpbin.org431 <Response [200]>432433.. _custom-auth:434435Custom Authentication436---------------------437438Requests allows you to use specify your own authentication mechanism.439440Any callable which is passed as the ``auth`` argument to a request method will441have the opportunity to modify the request before it is dispatched.442443Authentication implementations are subclasses of ``requests.auth.AuthBase``,444and are easy to define. Requests provides two common authentication scheme445implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.446447Let's pretend that we have a web service that will only respond if the448``X-Pizza`` header is set to a password value. Unlikely, but just go with it.449450::451452 from requests.auth import AuthBase453454 class PizzaAuth(AuthBase):455 """Attaches HTTP Pizza Authentication to the given Request object."""456 def __init__(self, username):457 # setup any auth-related data here458 self.username = username459460 def __call__(self, r):461 # modify and return the request462 r.headers['X-Pizza'] = self.username463 return r464465Then, we can make a request using our Pizza Auth::466467 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))468 <Response [200]>469470.. _streaming-requests:471472Streaming Requests473------------------474475With :class:`requests.Response.iter_lines()` you can easily476iterate over streaming APIs such as the `Twitter Streaming477API <https://dev.twitter.com/streaming/overview>`_. Simply478set ``stream`` to ``True`` and iterate over the response with479:class:`~requests.Response.iter_lines()`::480481 import json482 import requests483484 r = requests.get('http://httpbin.org/stream/20', stream=True)485486 for line in r.iter_lines():487488 # filter out keep-alive new lines489 if line:490 print(json.loads(line))491492.. warning::493494 :class:`~requests.Response.iter_lines()` is not reentrant safe.495 Calling this method multiple times causes some of the received data496 being lost. In case you need to call it from multiple places, use497 the resulting iterator object instead::498499 lines = r.iter_lines()500 # Save the first line for later or just skip it501502 first_line = next(lines)503504 for line in lines:505 print(line)506507.. _proxies:508509Proxies510-------511512If you need to use a proxy, you can configure individual requests with the513``proxies`` argument to any request method::514515 import requests516517 proxies = {518 'http': 'http://10.10.1.10:3128',519 'https': 'http://10.10.1.10:1080',520 }521522 requests.get('http://example.org', proxies=proxies)523524You can also configure proxies by setting the environment variables525``HTTP_PROXY`` and ``HTTPS_PROXY``.526527::528529 $ export HTTP_PROXY="http://10.10.1.10:3128"530 $ export HTTPS_PROXY="http://10.10.1.10:1080"531532 $ python533 >>> import requests534 >>> requests.get('http://example.org')535536To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::537538 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}539540To give a proxy for a specific scheme and host, use the541`scheme://hostname` form for the key. This will match for542any request to the given scheme and exact hostname.543544::545546 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}547548Note that proxy URLs must include the scheme.549550SOCKS551^^^^^552553.. versionadded:: 2.10.0554555In addition to basic HTTP proxies, requests also supports proxies using the556SOCKS protocol. This is an optional feature that requires that additional557third-party libraries be installed before use.558559You can get the dependencies for this feature from ``pip``:560561.. code-block:: bash562563 $ pip install requests[socks]564565Once you've installed those dependencies, using a SOCKS proxy is just as easy566as using a HTTP one::567568 proxies = {569 'http': 'socks5://user:pass@host:port',570 'https': 'socks5://user:pass@host:port'571 }572573.. _compliance:574575Compliance576----------577578Requests is intended to be compliant with all relevant specifications and579RFCs where that compliance will not cause difficulties for users. This580attention to the specification can lead to some behaviour that may seem581unusual to those not familiar with the relevant specification.582583Encodings584^^^^^^^^^585586When you receive a response, Requests makes a guess at the encoding to587use for decoding the response when you access the :attr:`Response.text588<requests.Response.text>` attribute. Requests will first check for an589encoding in the HTTP header, and if none is present, will use `chardet590<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.591592The only time Requests will not do this is if no explicit charset593is present in the HTTP headers **and** the ``Content-Type``594header contains ``text``. In this situation, `RFC 2616595<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies596that the default charset must be ``ISO-8859-1``. Requests follows the597specification in this case. If you require a different encoding, you can598manually set the :attr:`Response.encoding <requests.Response.encoding>`599property, or use the raw :attr:`Response.content <requests.Response.content>`.600601.. _http-verbs:602603HTTP Verbs604----------605606Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,607HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of608using these various verbs in Requests, using the GitHub API.609610We will begin with the verb most commonly used: GET. HTTP GET is an idempotent611method that returns a resource from a given URL. As a result, it is the verb612you ought to use when attempting to retrieve data from a web location. An613example usage would be attempting to get information about a specific commit614from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it615like so::616617 >>> import requests618 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')619620We should confirm that GitHub responded correctly. If it has, we want to work621out what type of content it is. Do this like so::622623 >>> if r.status_code == requests.codes.ok:624 ... print(r.headers['content-type'])625 ...626 application/json; charset=utf-8627628So, GitHub returns JSON. That's great, we can use the :meth:`r.json629<requests.Response.json>` method to parse it into Python objects.630631::632633 >>> commit_data = r.json()634635 >>> print(commit_data.keys())636 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']637638 >>> print(commit_data[u'committer'])639 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}640641 >>> print(commit_data[u'message'])642 makin' history643644So far, so simple. Well, let's investigate the GitHub API a little bit. Now,645we could look at the documentation, but we might have a little more fun if we646use Requests instead. We can take advantage of the Requests OPTIONS verb to647see what kinds of HTTP methods are supported on the url we just used.648649::650651 >>> verbs = requests.options(r.url)652 >>> verbs.status_code653 500654655Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't656actually implement the OPTIONS method. This is an annoying oversight, but it's657OK, we can just use the boring documentation. If GitHub had correctly658implemented OPTIONS, however, they should return the allowed methods in the659headers, e.g.660661::662663 >>> verbs = requests.options('http://a-good-website.com/api/cats')664 >>> print(verbs.headers['allow'])665 GET,HEAD,POST,OPTIONS666667Turning to the documentation, we see that the only other method allowed for668commits is POST, which creates a new commit. As we're using the Requests repo,669we should probably avoid making ham-handed POSTS to it. Instead, let's play670with the Issues feature of GitHub.671672This documentation was added in response to Issue #482. Given that this issue673already exists, we will use it as an example. Let's start by getting it.674675::676677 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')678 >>> r.status_code679 200680681 >>> issue = json.loads(r.text)682683 >>> print(issue[u'title'])684 Feature any http verb in docs685686 >>> print(issue[u'comments'])687 3688689Cool, we have three comments. Let's take a look at the last of them.690691::692693 >>> r = requests.get(r.url + u'/comments')694 >>> r.status_code695 200696697 >>> comments = r.json()698699 >>> print(comments[0].keys())700 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']701702 >>> print(comments[2][u'body'])703 Probably in the "advanced" section704705Well, that seems like a silly place. Let's post a comment telling the poster706that he's silly. Who is the poster, anyway?707708::709710 >>> print(comments[2][u'user'][u'login'])711 kennethreitz712713OK, so let's tell this Kenneth guy that we think this example should go in the714quickstart guide instead. According to the GitHub API doc, the way to do this715is to POST to the thread. Let's do it.716717::718719 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})720 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"721722 >>> r = requests.post(url=url, data=body)723 >>> r.status_code724 404725726Huh, that's weird. We probably need to authenticate. That'll be a pain, right?727Wrong. Requests makes it easy to use many forms of authentication, including728the very common Basic Auth.729730::731732 >>> from requests.auth import HTTPBasicAuth733 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')734735 >>> r = requests.post(url=url, data=body, auth=auth)736 >>> r.status_code737 201738739 >>> content = r.json()740 >>> print(content[u'body'])741 Sounds great! I'll get right on it.742743Brilliant. Oh, wait, no! I meant to add that it would take me a while, because744I had to go feed my cat. If only I could edit this comment! Happily, GitHub745allows us to use another HTTP verb, PATCH, to edit this comment. Let's do746that.747748::749750 >>> print(content[u"id"])751 5804413752753 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})754 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"755756 >>> r = requests.patch(url=url, data=body, auth=auth)757 >>> r.status_code758 200759760Excellent. Now, just to torture this Kenneth guy, I've decided to let him761sweat and not tell him that I'm working on this. That means I want to delete762this comment. GitHub lets us delete comments using the incredibly aptly named763DELETE method. Let's get rid of it.764765::766767 >>> r = requests.delete(url=url, auth=auth)768 >>> r.status_code769 204770 >>> r.headers['status']771 '204 No Content'772773Excellent. All gone. The last thing I want to know is how much of my ratelimit774I've used. Let's find out. GitHub sends that information in the headers, so775rather than download the whole page I'll send a HEAD request to get the776headers.777778::779780 >>> r = requests.head(url=url, auth=auth)781 >>> print(r.headers)782 ...783 'x-ratelimit-remaining': '4995'784 'x-ratelimit-limit': '5000'785 ...786787Excellent. Time to write a Python program that abuses the GitHub API in all788kinds of exciting ways, 4995 more times.789790.. _link-headers:791792Link Headers793------------794795Many HTTP APIs feature Link headers. They make APIs more self describing and796discoverable.797798GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_799in their API, for example::800801 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'802 >>> r = requests.head(url=url)803 >>> r.headers['link']804 '<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"'805806Requests will automatically parse these link headers and make them easily consumable::807808 >>> r.links["next"]809 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}810811 >>> r.links["last"]812 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}813814.. _transport-adapters:815816Transport Adapters817------------------818819As of v1.0.0, Requests has moved to a modular internal design. Part of the820reason this was done was to implement Transport Adapters, originally821`described here`_. Transport Adapters provide a mechanism to define interaction822methods for an HTTP service. In particular, they allow you to apply per-service823configuration.824825Requests ships with a single Transport Adapter, the :class:`HTTPAdapter826<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests827interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever828a Requests :class:`Session <requests.Session>` is initialized, one of these is829attached to the :class:`Session <requests.Session>` object for HTTP, and one830for HTTPS.831832Requests enables users to create and use their own Transport Adapters that833provide specific functionality. Once created, a Transport Adapter can be834mounted to a Session object, along with an indication of which web services835it should apply to.836837::838839 >>> s = requests.Session()840 >>> s.mount('http://www.github.com', MyAdapter())841842The mount call registers a specific instance of a Transport Adapter to a843prefix. Once mounted, any HTTP request made using that session whose URL starts844with the given prefix will use the given Transport Adapter.845846Many of the details of implementing a Transport Adapter are beyond the scope of847this documentation, but take a look at the next example for a simple SSL use-848case. For more than that, you might look at subclassing849``requests.adapters.BaseAdapter``.850851Example: Specific SSL Version852^^^^^^^^^^^^^^^^^^^^^^^^^^^^^853854The Requests team has made a specific choice to use whatever SSL version is855default in the underlying library (`urllib3`_). Normally this is fine, but from856time to time, you might find yourself needing to connect to a service-endpoint857that uses a version that isn't compatible with the default.858859You can use Transport Adapters for this by taking most of the existing860implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets861passed-through to `urllib3`. We'll make a TA that instructs the library to use862SSLv3:863864::865866 import ssl867868 from requests.adapters import HTTPAdapter869 from requests.packages.urllib3.poolmanager import PoolManager870871872 class Ssl3HttpAdapter(HTTPAdapter):873 """"Transport adapter" that allows us to use SSLv3."""874875 def init_poolmanager(self, connections, maxsize, block=False):876 self.poolmanager = PoolManager(877 num_pools=connections, maxsize=maxsize,878 block=block, ssl_version=ssl.PROTOCOL_SSLv3)879880.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http881.. _`urllib3`: https://github.com/shazow/urllib3882883.. _blocking-or-nonblocking:884885Blocking Or Non-Blocking?886-------------------------887888With the default Transport Adapter in place, Requests does not provide any kind889of non-blocking IO. The :attr:`Response.content <requests.Response.content>`890property will block until the entire response has been downloaded. If891you require more granularity, the streaming features of the library (see892:ref:`streaming-requests`) allow you to retrieve smaller quantities of the893response at a time. However, these calls will still block.894895If you are concerned about the use of blocking IO, there are lots of projects896out there that combine Requests with one of Python's asynchronicity frameworks.897Two excellent examples are `grequests`_ and `requests-futures`_.898899.. _`grequests`: https://github.com/kennethreitz/grequests900.. _`requests-futures`: https://github.com/ross/requests-futures901902.. _timeouts:903904Timeouts905--------906907Most requests to external servers should have a timeout attached, in case the908server is not responding in a timely manner. Without a timeout, your code may909hang for minutes or more.910911The **connect** timeout is the number of seconds Requests will wait for your912client to establish a connection to a remote machine (corresponding to the913`connect()`_) call on the socket. It's a good practice to set connect timeouts914to slightly larger than a multiple of 3, which is the default `TCP packet915retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.916917Once your client has connected to the server and sent the HTTP request, the918**read** timeout is the number of seconds the client will wait for the server919to send a response. (Specifically, it's the number of seconds that the client920will wait *between* bytes sent from the server. In 99.9% of cases, this is the921time before the server sends the first byte).922923If you specify a single value for the timeout, like this::924925 r = requests.get('https://github.com', timeout=5)926927The timeout value will be applied to both the ``connect`` and the ``read``928timeouts. Specify a tuple if you would like to set the values separately::929930 r = requests.get('https://github.com', timeout=(3.05, 27))931932If the remote server is very slow, you can tell Requests to wait forever for933a response, by passing None as a timeout value and then retrieving a cup of934coffee.935936.. code-block:: python937938 r = requests.get('https://github.com', timeout=None)939940.. _`connect()`: http://linux.die.net/man/2/connect