advanced.rst
This file
Path
docs/user/advanced.rst
743 lines · 25.9 KiB
Last changed by
Revert "Documentation update : connection keep alive"Kenneth Reitzbefore adoption1fcda91
History of this fileTake it
1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.789Session Objects10---------------1112The Session object allows you to persist certain parameters across13requests. It also persists cookies across all requests made from the14Session instance.1516A Session object has all the methods of the main Requests API.1718Let's persist some cookies across requests::1920 s = requests.Session()2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print(r.text)26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods. This30is done by providing data to the properties on a Session object::3132 s = requests.Session()33 s.auth = ('user', 'pass')34 s.headers.update({'x-test': 'true'})3536 # both 'x-test' and 'x-test2' are sent37 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})383940Any dictionaries that you pass to a request method will be merged with the41session-level values that are set. The method-level parameters override session42parameters.4344.. admonition:: Remove a Value From a Dict Parameter4546 Sometimes you'll want to omit session-level keys from a dict parameter. To47 do this, you simply set that key's value to ``None`` in the method-level48 parameter. It will automatically be omitted.4950All values that are contained within a session are directly available to you.51See the :ref:`Session API Docs <sessionapi>` to learn more.5253Request and Response Objects54----------------------------5556Whenever a call is made to ``requests.get()`` and friends you are doing two57major things. First, you are constructing a ``Request`` object which will be58sent off to a server to request or query some resource. Second, a ``Response``59object is generated once ``requests`` gets a response back from the server.60The Response object contains all of the information returned by the server and61also contains the ``Request`` object you created originally. Here is a simple62request to get some very important information from Wikipedia's servers::6364 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')6566If we want to access the headers the server sent back to us, we do this::6768 >>> r.headers69 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':70 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':71 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',72 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',73 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,74 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':75 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,76 MISS from cp1010.eqiad.wmnet:80'}7778However, if we want to get the headers we sent the server, we simply access the79request, and then the request's headers::8081 >>> r.request.headers82 {'Accept-Encoding': 'identity, deflate, compress, gzip',83 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}8485Prepared Requests86-----------------8788Whenever you receive a :class:`Response <requests.Response>` object89from an API call or a Session call, the ``request`` attribute is actually the90``PreparedRequest`` that was used. In some cases you may wish to do some extra91work to the body or headers (or anything else really) before sending a92request. The simple recipe for this is the following::9394 from requests import Request, Session9596 s = Session()97 req = Request('GET', url,98 data=data,99 headers=header100 )101 prepped = req.prepare()102103 # do something with prepped.body104 # do something with prepped.headers105106 resp = s.send(prepped,107 stream=stream,108 verify=verify,109 proxies=proxies,110 cert=cert,111 timeout=timeout112 )113114 print(resp.status_code)115116Since you are not doing anything special with the ``Request`` object, you117prepare it immediately and modify the ``PreparedRequest`` object. You then118send that with the other parameters you would have sent to ``requests.*`` or119``Session.*``.120121However, the above code will lose some of the advantages of having a Requests122:class:`Session <requests.Session>` object. In particular,123:class:`Session <requests.Session>`-level state such as cookies will124not get applied to your request. To get a125:class:`PreparedRequest <requests.PreparedRequest>` with that state126applied, replace the call to :meth:`Request.prepare()127<requests.Request.prepare>` with a call to128:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::129130 from requests import Request, Session131132 s = Session()133 req = Request('GET', url,134 data=data135 headers=headers136 )137138 prepped = s.prepare_request(req)139140 # do something with prepped.body141 # do something with prepped.headers142143 resp = s.send(prepped,144 stream=stream,145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150151 print(resp.status_code)152153.. _verification:154155SSL Cert Verification156---------------------157158Requests can verify SSL certificates for HTTPS requests, just like a web browser.159To check a host's SSL certificate, you can use the ``verify`` argument::160161 >>> requests.get('https://kennethreitz.com', verify=True)162 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'163164I don't have SSL setup on this domain, so it fails. Excellent. GitHub does though::165166 >>> requests.get('https://github.com', verify=True)167 <Response [200]>168169You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.170171Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.172173::174175 >>> requests.get('https://kennethreitz.com', verify=False)176 <Response [200]>177178By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.179180You can also specify a local cert to use as client side certificate, as a single181file (containing the private key and the certificate) or as a tuple of both182file's path::183184 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))185 <Response [200]>186187If you specify a wrong path or an invalid cert::188189 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')190 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib191192193Body Content Workflow194---------------------195196By default, when you make a request, the body of the response is downloaded197immediately. You can override this behavior and defer downloading the response198body until you access the :class:`Response.content <requests.Response.content>`199attribute with the ``stream`` parameter::200201 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'202 r = requests.get(tarball_url, stream=True)203204At this point only the response headers have been downloaded and the connection205remains open, hence allowing us to make content retrieval conditional::206207 if int(r.headers['content-length']) < TOO_LONG:208 content = r.content209 ...210211You can further control the workflow by use of the :class:`Response.iter_content <requests.Response.iter_content>`212and :class:`Response.iter_lines <requests.Response.iter_lines>` methods.213Alternatively, you can read the undecoded body from the underlying214urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at215:class:`Response.raw <requests.Response.raw>`.216217If you set ``stream`` to ``True`` when making a request, Requests cannot218release the connection back to the pool unless you consume all the data or call219:class:`Response.close <requests.Response.close>`. This can lead to220inefficiency with connections. If you find yourself partially reading request221bodies (or not reading them at all) while using ``stream=True``, you should222consider using ``contextlib.closing`` (`documented here`_), like this::223224 from contextlib import closing225226 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:227 # Do things with the response here.228229.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing230231232Keep-Alive233----------234235Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!236Any requests that you make within a session will automatically reuse the appropriate237connection!238239Note that connections are only released back to the pool for reuse once all body240data has been read; be sure to either set ``stream`` to ``False`` or read the241``content`` property of the ``Response`` object.242243244Streaming Uploads245-----------------246247Requests supports streaming uploads, which allow you to send large streams or248files without reading them into memory. To stream and upload, simply provide a249file-like object for your body::250251 with open('massive-body', 'rb') as f:252 requests.post('http://some.url/streamed', data=f)253254255Chunk-Encoded Requests256----------------------257258Requests also supports Chunked transfer encoding for outgoing and incoming requests.259To send a chunk-encoded request, simply provide a generator (or any iterator without260a length) for your body::261262263 def gen():264 yield 'hi'265 yield 'there'266267 requests.post('http://some.url/chunked', data=gen())268269270Event Hooks271-----------272273Requests has a hook system that you can use to manipulate portions of274the request process, or signal event handling.275276Available hooks:277278``response``:279 The response generated from a Request.280281282You can assign a hook function on a per-request basis by passing a283``{hook_name: callback_function}`` dictionary to the ``hooks`` request284parameter::285286 hooks=dict(response=print_url)287288That ``callback_function`` will receive a chunk of data as its first289argument.290291::292293 def print_url(r, *args, **kwargs):294 print(r.url)295296If an error occurs while executing your callback, a warning is given.297298If the callback function returns a value, it is assumed that it is to299replace the data that was passed in. If the function doesn't return300anything, nothing else is effected.301302Let's print some request method arguments at runtime::303304 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))305 http://httpbin.org306 <Response [200]>307308309Custom Authentication310---------------------311312Requests allows you to use specify your own authentication mechanism.313314Any callable which is passed as the ``auth`` argument to a request method will315have the opportunity to modify the request before it is dispatched.316317Authentication implementations are subclasses of ``requests.auth.AuthBase``,318and are easy to define. Requests provides two common authentication scheme319implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.320321Let's pretend that we have a web service that will only respond if the322``X-Pizza`` header is set to a password value. Unlikely, but just go with it.323324::325326 from requests.auth import AuthBase327328 class PizzaAuth(AuthBase):329 """Attaches HTTP Pizza Authentication to the given Request object."""330 def __init__(self, username):331 # setup any auth-related data here332 self.username = username333334 def __call__(self, r):335 # modify and return the request336 r.headers['X-Pizza'] = self.username337 return r338339Then, we can make a request using our Pizza Auth::340341 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))342 <Response [200]>343344.. _streaming-requests:345346Streaming Requests347------------------348349With :class:`requests.Response.iter_lines()` you can easily350iterate over streaming APIs such as the `Twitter Streaming351API <https://dev.twitter.com/docs/streaming-api>`_. Simply352set ``stream`` to ``True`` and iterate over the response with353:class:`~requests.Response.iter_lines()`::354355 import json356 import requests357358 r = requests.get('http://httpbin.org/stream/20', stream=True)359360 for line in r.iter_lines():361362 # filter out keep-alive new lines363 if line:364 print(json.loads(line))365366367Proxies368-------369370If you need to use a proxy, you can configure individual requests with the371``proxies`` argument to any request method::372373 import requests374375 proxies = {376 "http": "http://10.10.1.10:3128",377 "https": "http://10.10.1.10:1080",378 }379380 requests.get("http://example.org", proxies=proxies)381382You can also configure proxies by setting the environment variables383``HTTP_PROXY`` and ``HTTPS_PROXY``.384385::386387 $ export HTTP_PROXY="http://10.10.1.10:3128"388 $ export HTTPS_PROXY="http://10.10.1.10:1080"389 $ python390 >>> import requests391 >>> requests.get("http://example.org")392393To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::394395 proxies = {396 "http": "http://user:pass@10.10.1.10:3128/",397 }398399Note that proxy URLs must include the scheme.400401Compliance402----------403404Requests is intended to be compliant with all relevant specifications and405RFCs where that compliance will not cause difficulties for users. This406attention to the specification can lead to some behaviour that may seem407unusual to those not familiar with the relevant specification.408409Encodings410^^^^^^^^^411412When you receive a response, Requests makes a guess at the encoding to413use for decoding the response when you access the :attr:`Response.text414<requests.Response.text>` attribute. Requests will first check for an415encoding in the HTTP header, and if none is present, will use `chardet416<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.417418The only time Requests will not do this is if no explicit charset419is present in the HTTP headers **and** the ``Content-Type``420header contains ``text``. In this situation, `RFC 2616421<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies422that the default charset must be ``ISO-8859-1``. Requests follows the423specification in this case. If you require a different encoding, you can424manually set the :attr:`Response.encoding <requests.Response.encoding>`425property, or use the raw :attr:`Response.content <requests.Response.content>`.426427HTTP Verbs428----------429430Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,431HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of432using these various verbs in Requests, using the GitHub API.433434We will begin with the verb most commonly used: GET. HTTP GET is an idempotent435method that returns a resource from a given URL. As a result, it is the verb436you ought to use when attempting to retrieve data from a web location. An437example usage would be attempting to get information about a specific commit438from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it439like so::440441 >>> import requests442 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')443444We should confirm that GitHub responded correctly. If it has, we want to work445out what type of content it is. Do this like so::446447 >>> if r.status_code == requests.codes.ok:448 ... print(r.headers['content-type'])449 ...450 application/json; charset=utf-8451452So, GitHub returns JSON. That's great, we can use the :meth:`r.json453<requests.Response.json>` method to parse it into Python objects.454455::456457 >>> commit_data = r.json()458 >>> print(commit_data.keys())459 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']460 >>> print(commit_data[u'committer'])461 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}462 >>> print(commit_data[u'message'])463 makin' history464465So far, so simple. Well, let's investigate the GitHub API a little bit. Now,466we could look at the documentation, but we might have a little more fun if we467use Requests instead. We can take advantage of the Requests OPTIONS verb to468see what kinds of HTTP methods are supported on the url we just used.469470::471472 >>> verbs = requests.options(r.url)473 >>> verbs.status_code474 500475476Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't477actually implement the OPTIONS method. This is an annoying oversight, but it's478OK, we can just use the boring documentation. If GitHub had correctly479implemented OPTIONS, however, they should return the allowed methods in the480headers, e.g.481482::483484 >>> verbs = requests.options('http://a-good-website.com/api/cats')485 >>> print(verbs.headers['allow'])486 GET,HEAD,POST,OPTIONS487488Turning to the documentation, we see that the only other method allowed for489commits is POST, which creates a new commit. As we're using the Requests repo,490we should probably avoid making ham-handed POSTS to it. Instead, let's play491with the Issues feature of GitHub.492493This documentation was added in response to Issue #482. Given that this issue494already exists, we will use it as an example. Let's start by getting it.495496::497498 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')499 >>> r.status_code500 200501 >>> issue = json.loads(r.text)502 >>> print(issue[u'title'])503 Feature any http verb in docs504 >>> print(issue[u'comments'])505 3506507Cool, we have three comments. Let's take a look at the last of them.508509::510511 >>> r = requests.get(r.url + u'/comments')512 >>> r.status_code513 200514 >>> comments = r.json()515 >>> print(comments[0].keys())516 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']517 >>> print(comments[2][u'body'])518 Probably in the "advanced" section519520Well, that seems like a silly place. Let's post a comment telling the poster521that he's silly. Who is the poster, anyway?522523::524525 >>> print(comments[2][u'user'][u'login'])526 kennethreitz527528OK, so let's tell this Kenneth guy that we think this example should go in the529quickstart guide instead. According to the GitHub API doc, the way to do this530is to POST to the thread. Let's do it.531532::533534 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})535 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"536 >>> r = requests.post(url=url, data=body)537 >>> r.status_code538 404539540Huh, that's weird. We probably need to authenticate. That'll be a pain, right?541Wrong. Requests makes it easy to use many forms of authentication, including542the very common Basic Auth.543544::545546 >>> from requests.auth import HTTPBasicAuth547 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')548 >>> r = requests.post(url=url, data=body, auth=auth)549 >>> r.status_code550 201551 >>> content = r.json()552 >>> print(content[u'body'])553 Sounds great! I'll get right on it.554555Brilliant. Oh, wait, no! I meant to add that it would take me a while, because556I had to go feed my cat. If only I could edit this comment! Happily, GitHub557allows us to use another HTTP verb, PATCH, to edit this comment. Let's do558that.559560::561562 >>> print(content[u"id"])563 5804413564 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})565 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"566 >>> r = requests.patch(url=url, data=body, auth=auth)567 >>> r.status_code568 200569570Excellent. Now, just to torture this Kenneth guy, I've decided to let him571sweat and not tell him that I'm working on this. That means I want to delete572this comment. GitHub lets us delete comments using the incredibly aptly named573DELETE method. Let's get rid of it.574575::576577 >>> r = requests.delete(url=url, auth=auth)578 >>> r.status_code579 204580 >>> r.headers['status']581 '204 No Content'582583Excellent. All gone. The last thing I want to know is how much of my ratelimit584I've used. Let's find out. GitHub sends that information in the headers, so585rather than download the whole page I'll send a HEAD request to get the586headers.587588::589590 >>> r = requests.head(url=url, auth=auth)591 >>> print(r.headers)592 ...593 'x-ratelimit-remaining': '4995'594 'x-ratelimit-limit': '5000'595 ...596597Excellent. Time to write a Python program that abuses the GitHub API in all598kinds of exciting ways, 4995 more times.599600Link Headers601------------602603Many HTTP APIs feature Link headers. They make APIs more self describing and604discoverable.605606GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_607in their API, for example::608609 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'610 >>> r = requests.head(url=url)611 >>> r.headers['link']612 '<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"'613614Requests will automatically parse these link headers and make them easily consumable::615616 >>> r.links["next"]617 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}618619 >>> r.links["last"]620 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}621622Transport Adapters623------------------624625As of v1.0.0, Requests has moved to a modular internal design. Part of the626reason this was done was to implement Transport Adapters, originally627`described here`_. Transport Adapters provide a mechanism to define interaction628methods for an HTTP service. In particular, they allow you to apply per-service629configuration.630631Requests ships with a single Transport Adapter, the :class:`HTTPAdapter632<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests633interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever634a Requests :class:`Session <requests.Session>` is initialized, one of these is635attached to the :class:`Session <requests.Session>` object for HTTP, and one636for HTTPS.637638Requests enables users to create and use their own Transport Adapters that639provide specific functionality. Once created, a Transport Adapter can be640mounted to a Session object, along with an indication of which web services641it should apply to.642643::644645 >>> s = requests.Session()646 >>> s.mount('http://www.github.com', MyAdapter())647648The mount call registers a specific instance of a Transport Adapter to a649prefix. Once mounted, any HTTP request made using that session whose URL starts650with the given prefix will use the given Transport Adapter.651652Many of the details of implementing a Transport Adapter are beyond the scope of653this documentation, but take a look at the next example for a simple SSL use-654case. For more than that, you might look at subclassing655``requests.adapters.BaseAdapter``.656657Example: Specific SSL Version658^^^^^^^^^^^^^^^^^^^^^^^^^^^^^659660The Requests team has made a specific choice to use whatever SSL version is661default in the underlying library (`urllib3`_). Normally this is fine, but from662time to time, you might find yourself needing to connect to a service-endpoint663that uses a version that isn't compatible with the default.664665You can use Transport Adapters for this by taking most of the existing666implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets667passed-through to `urllib3`. We'll make a TA that instructs the library to use668SSLv3:669670::671672 import ssl673674 from requests.adapters import HTTPAdapter675 from requests.packages.urllib3.poolmanager import PoolManager676677678 class Ssl3HttpAdapter(HTTPAdapter):679 """"Transport adapter" that allows us to use SSLv3."""680681 def init_poolmanager(self, connections, maxsize, block=False):682 self.poolmanager = PoolManager(num_pools=connections,683 maxsize=maxsize,684 block=block,685 ssl_version=ssl.PROTOCOL_SSLv3)686687.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http688.. _`urllib3`: https://github.com/shazow/urllib3689690Blocking Or Non-Blocking?691-------------------------692693With the default Transport Adapter in place, Requests does not provide any kind694of non-blocking IO. The :attr:`Response.content <requests.Response.content>`695property will block until the entire response has been downloaded. If696you require more granularity, the streaming features of the library (see697:ref:`streaming-requests`) allow you to retrieve smaller quantities of the698response at a time. However, these calls will still block.699700If you are concerned about the use of blocking IO, there are lots of projects701out there that combine Requests with one of Python's asynchronicity frameworks.702Two excellent examples are `grequests`_ and `requests-futures`_.703704.. _`grequests`: https://github.com/kennethreitz/grequests705.. _`requests-futures`: https://github.com/ross/requests-futures706707Timeouts708--------709710Most requests to external servers should have a timeout attached, in case the711server is not responding in a timely manner. Without a timeout, your code may712hang for minutes or more.713714The **connect** timeout is the number of seconds Requests will wait for your715client to establish a connection to a remote machine (corresponding to the716`connect()`_) call on the socket. It's a good practice to set connect timeouts717to slightly larger than a multiple of 3, which is the default `TCP packet718retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.719720Once your client has connected to the server and sent the HTTP request, the721**read** timeout is the number of seconds the client will wait for the server722to send a response. (Specifically, it's the number of seconds that the client723will wait *between* bytes sent from the server. In 99.9% of cases, this is the724time before the server sends the first byte).725726If you specify a single value for the timeout, like this::727728 r = requests.get('https://github.com', timeout=5)729730The timeout value will be applied to both the ``connect`` and the ``read``731timeouts. Specify a tuple if you would like to set the values separately::732733 r = requests.get('https://github.com', timeout=(3.05, 27))734735If the remote server is very slow, you can tell Requests to wait forever for736a response, by passing None as a timeout value and then retrieving a cup of737coffee.738739.. code-block:: python740741 r = requests.get('https://github.com', timeout=None)742743.. _`connect()`: http://linux.die.net/man/2/connect