advanced.rst
This file
Path
docs/user/advanced.rst
628 lines · 22.0 KiB
Last changed by
further cleanup examplesKenneth Reitzbefore adoptionebdd5ca
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 the session-level values that are set. The method-level parameters override session parameters.4142.. admonition:: Remove a Value From a Dict Parameter4344 Sometimes you'll want to omit session-level keys from a dict parameter. To do this, you simply set that key's value to ``None`` in the method-level parameter. It will automatically be omitted.4546All values that are contained within a session are directly available to you. See the :ref:`Session API Docs <sessionapi>` to learn more.4748Request and Response Objects49----------------------------5051Whenever a call is made to ``requests.get()`` and friends you are doing two52major things. First, you are constructing a ``Request`` object which will be53sent off to a server to request or query some resource. Second, a ``Response``54object is generated once ``requests`` gets a response back from the server.55The Response object contains all of the information returned by the server and56also contains the ``Request`` object you created originally. Here is a simple57request to get some very important information from Wikipedia's servers::5859 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')6061If we want to access the headers the server sent back to us, we do this::6263 >>> r.headers64 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':65 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':66 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',67 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',68 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,69 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':70 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,71 MISS from cp1010.eqiad.wmnet:80'}7273However, if we want to get the headers we sent the server, we simply access the74request, and then the request's headers::7576 >>> r.request.headers77 {'Accept-Encoding': 'identity, deflate, compress, gzip',78 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}7980Prepared Requests81-----------------8283Whenever you receive a :class:`Response <requests.models.Response>` object84from an API call or a Session call, the ``request`` attribute is actually the85``PreparedRequest`` that was used. In some cases you may wish to do some extra86work to the body or headers (or anything else really) before sending a87request. The simple recipe for this is the following::8889 from requests import Request, Session9091 s = Session()92 req = Request('GET', url,93 data=data,94 headers=header95 )96 prepped = req.prepare()9798 # do something with prepped.body99 # do something with prepped.headers100101 resp = s.send(prepped,102 stream=stream,103 verify=verify,104 proxies=proxies,105 cert=cert,106 timeout=timeout107 )108109 print(resp.status_code)110111Since you are not doing anything special with the ``Request`` object, you112prepare it immediately and modified the ``PreparedRequest`` object. You then113send that with the other parameters you would have sent to ``requests.*`` or114``Sesssion.*``.115116However, the above code will lose some of the advantages of having a Requests117:class:`Session <requests.Session>` object. In particular,118:class:`Session <requests.Session>`-level state such as cookies will119not get applied to your request. To get a120:class:`PreparedRequest <requests.models.PreparedRequest>` with that state121applied, replace the call to ``Request.prepare()`` with a call to122``Session.prepare_request()``, like this::123124 from requests import Request, Session125126 s = Session()127 req = Request('GET', url,128 data=data129 headers=headers130 )131132 prepped = s.prepare_request(req)133134 # do something with prepped.body135 # do something with prepped.headers136137 resp = s.send(prepped,138 stream=stream,139 verify=verify,140 proxies=proxies,141 cert=cert,142 timeout=timeout143 )144145 print(resp.status_code)146147SSL Cert Verification148---------------------149150Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host's SSL certificate, you can use the ``verify`` argument::151152 >>> requests.get('https://kennethreitz.com', verify=True)153 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'154155I don't have SSL setup on this domain, so it fails. Excellent. GitHub does though::156157 >>> requests.get('https://github.com', verify=True)158 <Response [200]>159160You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.161162Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.163164::165166 >>> requests.get('https://kennethreitz.com', verify=False)167 <Response [200]>168169By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.170171You can also specify a local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both file's path::172173 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))174 <Response [200]>175176If you specify a wrong path or an invalid cert::177178 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')179 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib180181182Body Content Workflow183---------------------184185By default, when you make a request, the body of the response is downloaded immediately. You can override this behavior and defer downloading the response body until you access the :class:`Response.content` attribute with the ``stream`` parameter::186187 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'188 r = requests.get(tarball_url, stream=True)189190At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::191192 if int(r.headers['content-length']) < TOO_LONG:193 content = r.content194 ...195196You can further control the workflow by use of the :class:`Response.iter_content` and :class:`Response.iter_lines` methods. Alternatively, you can read the undecoded body from the underlying urllib3 :class:`urllib3.HTTPResponse` at :class:`Response.raw`.197198199Keep-Alive200----------201202Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!203204Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``stream`` to ``False`` or read the ``content`` property of the ``Response`` object.205206207Streaming Uploads208-----------------209210Requests supports streaming uploads, which allow you to send large streams or files without reading them into memory. To stream and upload, simply provide a file-like object for your body::211212 with open('massive-body') as f:213 requests.post('http://some.url/streamed', data=f)214215216Chunk-Encoded Requests217----------------------218219Requests also supports Chunked transfer encoding for outgoing and incoming requests. To send a chunk-encoded request, simply provide a generator (or any iterator without a length) for your body::220221222 def gen():223 yield 'hi'224 yield 'there'225226 requests.post('http://some.url/chunked', data=gen())227228229Event Hooks230-----------231232Requests has a hook system that you can use to manipulate portions of233the request process, or signal event handling.234235Available hooks:236237``response``:238 The response generated from a Request.239240241You can assign a hook function on a per-request basis by passing a242``{hook_name: callback_function}`` dictionary to the ``hooks`` request243parameter::244245 hooks=dict(response=print_url)246247That ``callback_function`` will receive a chunk of data as its first248argument.249250::251252 def print_url(r, *args, **kwargs):253 print(r.url)254255If an error occurs while executing your callback, a warning is given.256257If the callback function returns a value, it is assumed that it is to258replace the data that was passed in. If the function doesn't return259anything, nothing else is effected.260261Let's print some request method arguments at runtime::262263 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))264 http://httpbin.org265 <Response [200]>266267268Custom Authentication269---------------------270271Requests allows you to use specify your own authentication mechanism.272273Any callable which is passed as the ``auth`` argument to a request method will274have the opportunity to modify the request before it is dispatched.275276Authentication implementations are subclasses of ``requests.auth.AuthBase``,277and are easy to define. Requests provides two common authentication scheme278implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.279280Let's pretend that we have a web service that will only respond if the281``X-Pizza`` header is set to a password value. Unlikely, but just go with it.282283::284285 from requests.auth import AuthBase286287 class PizzaAuth(AuthBase):288 """Attaches HTTP Pizza Authentication to the given Request object."""289 def __init__(self, username):290 # setup any auth-related data here291 self.username = username292293 def __call__(self, r):294 # modify and return the request295 r.headers['X-Pizza'] = self.username296 return r297298Then, we can make a request using our Pizza Auth::299300 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))301 <Response [200]>302303.. _streaming-requests304305Streaming Requests306------------------307308With ``requests.Response.iter_lines()`` you can easily iterate over streaming309APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.310Simply set ``stream`` to ``True`` and iterate over the response with ``iter_lines()``::311312 import json313 import requests314315 r = requests.get('http://httpbin.org/stream/20', stream=True)316317 for line in r.iter_lines():318319 # filter out keep-alive new lines320 if line:321 print json.loads(line)322323324Proxies325-------326327If you need to use a proxy, you can configure individual requests with the328``proxies`` argument to any request method::329330 import requests331332 proxies = {333 "http": "http://10.10.1.10:3128",334 "https": "http://10.10.1.10:1080",335 }336337 requests.get("http://example.org", proxies=proxies)338339You can also configure proxies by setting the environment variables340``HTTP_PROXY`` and ``HTTPS_PROXY``.341342::343344 $ export HTTP_PROXY="http://10.10.1.10:3128"345 $ export HTTPS_PROXY="http://10.10.1.10:1080"346 $ python347 >>> import requests348 >>> requests.get("http://example.org")349350To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::351352 proxies = {353 "http": "http://user:pass@10.10.1.10:3128/",354 }355356Note that proxy URLs must include the scheme.357358Compliance359----------360361Requests is intended to be compliant with all relevant specifications and362RFCs where that compliance will not cause difficulties for users. This363attention to the specification can lead to some behaviour that may seem364unusual to those not familiar with the relevant specification.365366Encodings367^^^^^^^^^368369When you receive a response, Requests makes a guess at the encoding to use for370decoding the response when you call the ``Response.text`` method. Requests371will first check for an encoding in the HTTP header, and if none is present,372will use `charade <http://pypi.python.org/pypi/charade>`_ to attempt to guess373the encoding.374375The only time Requests will not do this is if no explicit charset is present376in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In377this situation,378`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_379specifies that the default charset must be ``ISO-8859-1``. Requests follows380the specification in this case. If you require a different encoding, you can381manually set the ``Response.encoding`` property, or use the raw382``Response.content``.383384HTTP Verbs385----------386387Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,388HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of389using these various verbs in Requests, using the GitHub API.390391We will begin with the verb most commonly used: GET. HTTP GET is an idempotent392method that returns a resource from a given URL. As a result, it is the verb393you ought to use when attempting to retrieve data from a web location. An394example usage would be attempting to get information about a specific commit395from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it396like so::397398 >>> import requests399 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')400401We should confirm that GitHub responded correctly. If it has, we want to work402out what type of content it is. Do this like so::403404 >>> if (r.status_code == requests.codes.ok):405 ... print r.headers['content-type']406 ...407 application/json; charset=utf-8408409So, GitHub returns JSON. That's great, we can use the ``r.json`` method to410parse it into Python objects.411412::413414 >>> commit_data = r.json()415 >>> print commit_data.keys()416 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']417 >>> print commit_data[u'committer']418 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}419 >>> print commit_data[u'message']420 makin' history421422So far, so simple. Well, let's investigate the GitHub API a little bit. Now,423we could look at the documentation, but we might have a little more fun if we424use Requests instead. We can take advantage of the Requests OPTIONS verb to425see what kinds of HTTP methods are supported on the url we just used.426427::428429 >>> verbs = requests.options(r.url)430 >>> verbs.status_code431 500432433Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't434actually implement the OPTIONS method. This is an annoying oversight, but it's435OK, we can just use the boring documentation. If GitHub had correctly436implemented OPTIONS, however, they should return the allowed methods in the437headers, e.g.438439::440441 >>> verbs = requests.options('http://a-good-website.com/api/cats')442 >>> print verbs.headers['allow']443 GET,HEAD,POST,OPTIONS444445Turning to the documentation, we see that the only other method allowed for446commits is POST, which creates a new commit. As we're using the Requests repo,447we should probably avoid making ham-handed POSTS to it. Instead, let's play448with the Issues feature of GitHub.449450This documentation was added in response to Issue #482. Given that this issue451already exists, we will use it as an example. Let's start by getting it.452453::454455 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')456 >>> r.status_code457 200458 >>> issue = json.loads(r.text)459 >>> print issue[u'title']460 Feature any http verb in docs461 >>> print issue[u'comments']462 3463464Cool, we have three comments. Let's take a look at the last of them.465466::467468 >>> r = requests.get(r.url + u'/comments')469 >>> r.status_code470 200471 >>> comments = r.json()472 >>> print comments[0].keys()473 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']474 >>> print comments[2][u'body']475 Probably in the "advanced" section476477Well, that seems like a silly place. Let's post a comment telling the poster478that he's silly. Who is the poster, anyway?479480::481482 >>> print comments[2][u'user'][u'login']483 kennethreitz484485OK, so let's tell this Kenneth guy that we think this example should go in the486quickstart guide instead. According to the GitHub API doc, the way to do this487is to POST to the thread. Let's do it.488489::490491 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})492 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"493 >>> r = requests.post(url=url, data=body)494 >>> r.status_code495 404496497Huh, that's weird. We probably need to authenticate. That'll be a pain, right?498Wrong. Requests makes it easy to use many forms of authentication, including499the very common Basic Auth.500501::502503 >>> from requests.auth import HTTPBasicAuth504 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')505 >>> r = requests.post(url=url, data=body, auth=auth)506 >>> r.status_code507 201508 >>> content = r.json()509 >>> print content[u'body']510 Sounds great! I'll get right on it.511512Brilliant. Oh, wait, no! I meant to add that it would take me a while, because513I had to go feed my cat. If only I could edit this comment! Happily, GitHub514allows us to use another HTTP verb, PATCH, to edit this comment. Let's do515that.516517::518519 >>> print content[u"id"]520 5804413521 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})522 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"523 >>> r = requests.patch(url=url, data=body, auth=auth)524 >>> r.status_code525 200526527Excellent. Now, just to torture this Kenneth guy, I've decided to let him528sweat and not tell him that I'm working on this. That means I want to delete529this comment. GitHub lets us delete comments using the incredibly aptly named530DELETE method. Let's get rid of it.531532::533534 >>> r = requests.delete(url=url, auth=auth)535 >>> r.status_code536 204537 >>> r.headers['status']538 '204 No Content'539540Excellent. All gone. The last thing I want to know is how much of my ratelimit541I've used. Let's find out. GitHub sends that information in the headers, so542rather than download the whole page I'll send a HEAD request to get the543headers.544545::546547 >>> r = requests.head(url=url, auth=auth)548 >>> print r.headers549 ...550 'x-ratelimit-remaining': '4995'551 'x-ratelimit-limit': '5000'552 ...553554Excellent. Time to write a Python program that abuses the GitHub API in all555kinds of exciting ways, 4995 more times.556557Link Headers558------------559560Many HTTP APIs feature Link headers. They make APIs more self describing and discoverable.561562GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_ in their API, for example::563564 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'565 >>> r = requests.head(url=url)566 >>> r.headers['link']567 '<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"'568569Requests will automatically parse these link headers and make them easily consumable::570571 >>> r.links["next"]572 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}573574 >>> r.links["last"]575 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}576577Transport Adapters578------------------579580As of v1.0.0, Requests has moved to a modular internal design. Part of the581reason this was done was to implement Transport Adapters, originally582`described here`_. Transport Adapters provide a mechanism to define interaction583methods for an HTTP service. In particular, they allow you to apply per-service584configuration.585586Requests ships with a single Transport Adapter, the587:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This adapter provides the588default Requests interaction with HTTP and HTTPS using the powerful `urllib3`_589library. Whenever a Requests :class:`Session <Session>` is initialized, one of590these is attached to the :class:`Session <Session>` object for HTTP, and one591for HTTPS.592593Requests enables users to create and use their own Transport Adapters that594provide specific functionality. Once created, a Transport Adapter can be595mounted to a Session object, along with an indication of which web services596it should apply to.597598::599600 >>> s = requests.Session()601 >>> s.mount('http://www.github.com', MyAdapter())602603The mount call registers a specific instance of a Transport Adapter to a604prefix. Once mounted, any HTTP request made using that session whose URL starts605with the given prefix will use the given Transport Adapter.606607Implementing a Transport Adapter is beyond the scope of this documentation, but608a good start would be to subclass the ``requests.adapters.BaseAdapter`` class.609610.. _`described here`: http://kennethreitz.org/exposures/the-future-of-python-http611.. _`urllib3`: https://github.com/shazow/urllib3612613Blocking Or Non-Blocking?614-------------------------615616With the default Transport Adapter in place, Requests does not provide any kind617of non-blocking IO. The ``Response.content`` property will block until the618entire response has been downloaded. If you require more granularity, the619streaming features of the library (see :ref:`streaming-requests`) allow you to620retrieve smaller quantities of the response at a time. However, these calls621will still block.622623If you are concerned about the use of blocking IO, there are lots of projects624out there that combine Requests with one of Python's asynchronicity frameworks.625Two excellent examples are `grequests`_ and `requests-futures`_.626627.. _`grequests`: https://github.com/kennethreitz/grequests628.. _`requests-futures`: https://github.com/ross/requests-futures