advanced.rst
This file
Path
docs/user/advanced.rst
505 lines · 17.7 KiB
Last changed by
Merge pull request #1152 from ekatsah/patch-1Kenneth Reitzbefore adoptionb554b0c
History of this fileTake it
The walk stopped after 200 commits: lines older than 1960dab point at it.
out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 1–19why, one step back1.. _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::19update docsKenneth Reitzbefore adoption5b5ff69
line 20why, one step back20 s = requests.Session()out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 21–28why, one step back2122 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')23 r = s.get("http://httpbin.org/cookies")2425 print r.text26 # '{"cookies": {"sessioncookie": "123456789"}}'2728Merge pull request #1059 from Lukasa/sess_docsKenneth Reitzbefore adoptione23343a
lines 29–30why, one step back29Sessions can also be used to provide default data to the request methods. This30is done by providing data to the properties on a session object::out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
line 31why, one step back31update docsKenneth Reitzbefore adoption5b5ff69
lines 32–34why, one step back32 s = requests.Session()33 s.auth = ('user', 'pass')34 s.headers.update({'x-test': 'true'})out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
line 35why, one step back35update docsKenneth Reitzbefore adoption5b5ff69
lines 36–37why, one step back36 # both 'x-test' and 'x-test2' are sent37 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 38–58why, one step back383940Any 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.*() you are doing two major things. First,52you are constructing a ``Request`` object which will be sent of to a server53to request or query some resource. Second, a ``Response`` object is generated54once ``requests`` gets a response back from the server. The response object55contains all of the information returned by the server and also contains the56``Request`` object you created originally. Here is a simple request to get some57very important information from Wikipedia's servers::58update docsKenneth Reitzbefore adoption5b5ff69
line 59why, one step back59 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 60–62why, one step back6061If we want to access the headers the server sent back to us, we do this::62update docsKenneth Reitzbefore adoption5b5ff69
line 63why, one step back63 >>> r.headersout with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 64–75why, one step back64 {'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::75update docsKenneth Reitzbefore adoption5b5ff69
line 76why, one step back76 >>> r.request.headersout with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 77–104why, one step back77 {'Accept-Encoding': 'identity, deflate, compress, gzip',78 'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}798081SSL Cert Verification82---------------------8384Requests 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::8586 >>> requests.get('https://kennethreitz.com', verify=True)87 requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'8889I don't have SSL setup on this domain, so it fails. Excellent. Github does though::9091 >>> requests.get('https://github.com', verify=True)92 <Response [200]>9394You can also pass ``verify`` the path to a CA_BUNDLE file for private certs. You can also set the ``REQUESTS_CA_BUNDLE`` environment variable.9596Requests can also ignore verifying the SSL certficate if you set ``verify`` to False.9798::99100 >>> requests.get('https://kennethreitz.com', verify=False)101 <Response [200]>102103By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.104Merge pull request #1152 from ekatsah/patch-1Kenneth Reitzbefore adoptionb554b0c
line 105why, one step back105You 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::out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 106–118why, one step back106107 >>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))108 <Response [200]>109110If you specify a wrong path or an invalid cert::111112 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')113 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib114115116Body Content Workflow117---------------------118update docsKenneth Reitzbefore adoption1451ba0
line 119why, one step back119By 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::out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 120–121why, one step back120121 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'update docsKenneth Reitzbefore adoption1451ba0
line 122why, one step back122 r = requests.get(tarball_url, stream=True)out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 123–137why, one step back123124At this point only the response headers have been downloaded and the connection remains open, hence allowing us to make content retrieval conditional::125126 if int(r.headers['content-length']) < TOO_LONG:127 content = r.content128 ...129130You can further control the workflow by use of the :class:`Response.iter_content` and :class:`Response.iter_lines` methods, or reading from the underlying urllib3 :class:`urllib3.HTTPResponse` at :class:`Response.raw`.131132133Keep-Alive134----------135136Excellent 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!137update docsKenneth Reitzbefore adoption1451ba0
line 138why, one step back138Note 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.out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 139–140why, one step back139140v1.1.0 and docsKenneth Reitzbefore adoption41687c8
lines 141–146why, one step back141Streaming Uploads142-----------------143144Requests 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::145146 with open('massive-body') as f:Merge pull request #1121 from Lukasa/typoKenneth Reitzbefore adoption47aa968
line 147why, one step back147 requests.post('http://some.url/streamed', data=f)v1.1.0 and docsKenneth Reitzbefore adoption41687c8
lines 148–159why, one step back148149150Chunk-Encoded Requests151----------------------152153Requests 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::154155156 def gen():157 yield 'hi'158 yield 'there'159Merge pull request #1121 from Lukasa/typoKenneth Reitzbefore adoption47aa968
line 160why, one step back160 requests.post('http://some.url/chunked', data=gen())v1.1.0 and docsKenneth Reitzbefore adoption41687c8
lines 161–162why, one step back161162out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 163–178why, one step back163Event Hooks164-----------165166Requests has a hook system that you can use to manipulate portions of167the request process, or signal event handling.168169Available hooks:170171``response``:172 The response generated from a Request.173174175You can assign a hook function on a per-request basis by passing a176``{hook_name: callback_function}`` dictionary to the ``hooks`` request177parameter::178update docsKenneth Reitzbefore adoption1451ba0
line 179why, one step back179 hooks=dict(response=print_url)out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 180–185why, one step back180181That ``callback_function`` will receive a chunk of data as its first182argument.183184::185update docsKenneth Reitzbefore adoption1451ba0
lines 186–187why, one step back186 def print_url(r):187 print(r.url)out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 188–196why, one step back188189If an error occurs while executing your callback, a warning is given.190191If the callback function returns a value, it is assumed that it is to192replace the data that was passed in. If the function doesn't return193anything, nothing else is effected.194195Let's print some request method arguments at runtime::196update docsKenneth Reitzbefore adoption1451ba0
line 197why, one step back197 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 198–219why, one step back198 http://httpbin.org199 <Response [200]>200201202Custom Authentication203---------------------204205Requests allows you to use specify your own authentication mechanism.206207Any callable which is passed as the ``auth`` argument to a request method will208have the opportunity to modify the request before it is dispatched.209210Authentication implementations are subclasses of ``requests.auth.AuthBase``,211and are easy to define. Requests provides two common authentication scheme212implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.213214Let's pretend that we have a web service that will only respond if the215``X-Pizza`` header is set to a password value. Unlikely, but just go with it.216217::218219 from requests.auth import AuthBaseupdate docsKenneth Reitzbefore adoption5b5ff69
line 220why, one step back220out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 221–248why, one step back221 class PizzaAuth(AuthBase):222 """Attaches HTTP Pizza Authentication to the given Request object."""223 def __init__(self, username):224 # setup any auth-related data here225 self.username = username226227 def __call__(self, r):228 # modify and return the request229 r.headers['X-Pizza'] = self.username230 return r231232Then, we can make a request using our Pizza Auth::233234 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))235 <Response [200]>236237Streaming Requests238------------------239240With ``requests.Response.iter_lines()`` you can easily iterate over streaming241APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.242243To use the Twitter Streaming API to track the keyword "requests"::244245 import requests246 import json247248 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',update docsKenneth Reitzbefore adoption1451ba0
line 249why, one step back249 data={'track': 'requests'}, auth=('username', 'password'), stream=True)out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 250–300why, one step back250251 for line in r.iter_lines():252 if line: # filter out keep-alive new lines253 print json.loads(line)254255256Proxies257-------258259If you need to use a proxy, you can configure individual requests with the260``proxies`` argument to any request method::261262 import requests263264 proxies = {265 "http": "10.10.1.10:3128",266 "https": "10.10.1.10:1080",267 }268269 requests.get("http://example.org", proxies=proxies)270271You can also configure proxies by environment variables ``HTTP_PROXY`` and ``HTTPS_PROXY``.272273::274275 $ export HTTP_PROXY="10.10.1.10:3128"276 $ export HTTPS_PROXY="10.10.1.10:1080"277 $ python278 >>> import requests279 >>> requests.get("http://example.org")280281To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::282283 proxies = {284 "http": "http://user:pass@10.10.1.10:3128/",285 }286287Compliance288----------289290Requests is intended to be compliant with all relevant specifications and291RFCs where that compliance will not cause difficulties for users. This292attention to the specification can lead to some behaviour that may seem293unusual to those not familiar with the relevant specification.294295Encodings296^^^^^^^^^297298When you receive a response, Requests makes a guess at the encoding to use for299decoding the response when you call the ``Response.text`` method. Requests300will first check for an encoding in the HTTP header, and if none is present,update docsKenneth Reitzbefore adoption1451ba0
line 301why, one step back301will use `charade <http://pypi.python.org/pypi/charade>`_ to attempt to guessout with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 302–337why, one step back302the encoding.303304The only time Requests will not do this is if no explicit charset is present305in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In306this situation,307`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_308specifies that the default charset must be ``ISO-8859-1``. Requests follows309the specification in this case. If you require a different encoding, you can310manually set the ``Response.encoding`` property, or use the raw311``Response.content``.312313HTTP Verbs314----------315316Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,317HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of318using these various verbs in Requests, using the GitHub API.319320We will begin with the verb most commonly used: GET. HTTP GET is an idempotent321method that returns a resource from a given URL. As a result, it is the verb322you ought to use when attempting to retrieve data from a web location. An323example usage would be attempting to get information about a specific commit324from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it325like so::326327 >>> import requests328 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')329330We should confirm that GitHub responded correctly. If it has, we want to work331out what type of content it is. Do this like so::332333 >>> if (r.status_code == requests.codes.ok):334 ... print r.headers['content-type']335 ...336 application/json; charset=utf-8337Merge pull request #1085 from graingert/patch-1Kenneth Reitzbefore adoption47fe258
lines 338–339why, one step back338So, GitHub returns JSON. That's great, we can use the ``r.json`` method to339parse it into Python objects.out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 340–342why, one step back340341::342Merge pull request #1085 from graingert/patch-1Kenneth Reitzbefore adoption47fe258
line 343why, one step back343 >>> commit_data = r.json()out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 344–399why, one step back344 >>> print commit_data.keys()345 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']346 >>> print commit_data[u'committer']347 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}348 >>> print commit_data[u'message']349 makin' history350351So far, so simple. Well, let's investigate the GitHub API a little bit. Now,352we could look at the documentation, but we might have a little more fun if we353use Requests instead. We can take advantage of the Requests OPTIONS verb to354see what kinds of HTTP methods are supported on the url we just used.355356::357358 >>> verbs = requests.options(r.url)359 >>> verbs.status_code360 500361362Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't363actually implement the OPTIONS method. This is an annoying oversight, but it's364OK, we can just use the boring documentation. If GitHub had correctly365implemented OPTIONS, however, they should return the allowed methods in the366headers, e.g.367368::369370 >>> verbs = requests.options('http://a-good-website.com/api/cats')371 >>> print verbs.headers['allow']372 GET,HEAD,POST,OPTIONS373374Turning to the documentation, we see that the only other method allowed for375commits is POST, which creates a new commit. As we're using the Requests repo,376we should probably avoid making ham-handed POSTS to it. Instead, let's play377with the Issues feature of GitHub.378379This documentation was added in response to Issue #482. Given that this issue380already exists, we will use it as an example. Let's start by getting it.381382::383384 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')385 >>> r.status_code386 200387 >>> issue = json.loads(r.text)388 >>> print issue[u'title']389 Feature any http verb in docs390 >>> print issue[u'comments']391 3392393Cool, we have three comments. Let's take a look at the last of them.394395::396397 >>> r = requests.get(r.url + u'/comments')398 >>> r.status_code399 200Merge pull request #1085 from graingert/patch-1Kenneth Reitzbefore adoption47fe258
line 400why, one step back400 >>> comments = r.json()out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 401–436why, one step back401 >>> print comments[0].keys()402 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']403 >>> print comments[2][u'body']404 Probably in the "advanced" section405406Well, that seems like a silly place. Let's post a comment telling the poster407that he's silly. Who is the poster, anyway?408409::410411 >>> print comments[2][u'user'][u'login']412 kennethreitz413414OK, so let's tell this Kenneth guy that we think this example should go in the415quickstart guide instead. According to the GitHub API doc, the way to do this416is to POST to the thread. Let's do it.417418::419420 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})421 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"422 >>> r = requests.post(url=url, data=body)423 >>> r.status_code424 404425426Huh, that's weird. We probably need to authenticate. That'll be a pain, right?427Wrong. Requests makes it easy to use many forms of authentication, including428the very common Basic Auth.429430::431432 >>> from requests.auth import HTTPBasicAuth433 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')434 >>> r = requests.post(url=url, data=body, auth=auth)435 >>> r.status_code436 201Merge pull request #1085 from graingert/patch-1Kenneth Reitzbefore adoption47fe258
line 437why, one step back437 >>> content = r.json()out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
lines 438–499why, one step back438 >>> print content[u'body']439 Sounds great! I'll get right on it.440441Brilliant. Oh, wait, no! I meant to add that it would take me a while, because442I had to go feed my cat. If only I could edit this comment! Happily, GitHub443allows us to use another HTTP verb, PATCH, to edit this comment. Let's do444that.445446::447448 >>> print content[u"id"]449 5804413450 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})451 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"452 >>> r = requests.patch(url=url, data=body, auth=auth)453 >>> r.status_code454 200455456Excellent. Now, just to torture this Kenneth guy, I've decided to let him457sweat and not tell him that I'm working on this. That means I want to delete458this comment. GitHub lets us delete comments using the incredibly aptly named459DELETE method. Let's get rid of it.460461::462463 >>> r = requests.delete(url=url, auth=auth)464 >>> r.status_code465 204466 >>> r.headers['status']467 '204 No Content'468469Excellent. All gone. The last thing I want to know is how much of my ratelimit470I've used. Let's find out. GitHub sends that information in the headers, so471rather than download the whole page I'll send a HEAD request to get the472headers.473474::475476 >>> r = requests.head(url=url, auth=auth)477 >>> print r.headers478 ...479 'x-ratelimit-remaining': '4995'480 'x-ratelimit-limit': '5000'481 ...482483Excellent. Time to write a Python program that abuses the GitHub API in all484kinds of exciting ways, 4995 more times.485486Link Headers487------------488489Many HTTP APIs feature Link headers. They make APIs more self describing and discoverable.490491GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_ in their API, for example::492493 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'494 >>> r = requests.head(url=url)495 >>> r.headers['link']496 '<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"'497498Requests will automatically parse these link headers and make them easily consumable::499Merge pull request #1086 from graingert/patch-2Kenneth Reitzbefore adoption21616a8
lines 500–501why, one step back500 >>> r.links["next"]501 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
line 502why, one step back502Merge pull request #1086 from graingert/patch-2Kenneth Reitzbefore adoption21616a8
lines 503–504why, one step back503 >>> r.links["last"]504 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}out with chardet, in with charadeKenneth Reitzbefore adoption1960dab
line 505why, one step back505