advanced.rst
This file
Path
docs/user/advanced.rst
561 lines · 19.3 KiB
Last changed by
Merge remote-tracking branch 'origin/develop' into developKenneth Reitzbefore adoptionffc72ac
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.text26 # '{"cookies": {"sessioncookie": "123456789"}}'272829Sessions can also be used to provide default data to the request methods::3031 headers = {'x-test': 'true'}32 auth = ('user', 'pass')3334 with requests.session(auth=auth, headers=headers) as c:3536 # both 'x-test' and 'x-test2' are sent37 c.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.*() 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::5859 >>> response = 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 >>> response.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 >>> response.request.headers77 {'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.104105You can also specify the local cert file either as a path or key value pair::106107 >>> 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---------------------118119By 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 ``prefetch`` parameter::120121 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'122 r = requests.get(tarball_url, prefetch=False)123124At 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`.131132Note that in versions prior to 0.13.6 the ``prefetch`` default was set to ``False``.133134Configuring Requests135--------------------136137Sometimes you may want to configure a request to customize its behavior. To do138this, you can pass in a ``config`` dictionary to a request or session. See the :ref:`Configuration API Docs <configurations>` to learn more.139140141Keep-Alive142----------143144Excellent 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!145146Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set ``prefetch`` to ``True`` or read the ``content`` property of the ``Response`` object.147148If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::149150 s = requests.session()151 s.config['keep_alive'] = False152153154Asynchronous Requests155----------------------156157158``requests.async`` has been removed from requests and is now its own repository named `GRequests <https://github.com/kennethreitz/grequests>`_.159160161Event Hooks162-----------163164Requests has a hook system that you can use to manipulate portions of165the request process, or signal event handling.166167Available hooks:168169``args``:170 A dictionary of the arguments being sent to Request().171172``pre_request``:173 The Request object, directly before being sent.174175``post_request``:176 The Request object, directly after being sent.177178``response``:179 The response generated from a Request.180181182You can assign a hook function on a per-request basis by passing a183``{hook_name: callback_function}`` dictionary to the ``hooks`` request184parameter::185186 hooks=dict(args=print_url)187188That ``callback_function`` will receive a chunk of data as its first189argument.190191::192193 def print_url(args):194 print args['url']195196If an error occurs while executing your callback, a warning is given.197198If the callback function returns a value, it is assumed that it is to199replace the data that was passed in. If the function doesn't return200anything, nothing else is effected.201202Let's print some request method arguments at runtime::203204 >>> requests.get('http://httpbin.org', hooks=dict(args=print_url))205 http://httpbin.org206 <Response [200]>207208Let's hijack some arguments this time with a new callback::209210 def hack_headers(args):211 if args.get('headers') is None:212 args['headers'] = dict()213214 args['headers'].update({'X-Testing': 'True'})215216 return args217218 hooks = dict(args=hack_headers)219 headers = dict(yo=dawg)220221And give it a try::222223 >>> requests.get('http://httpbin.org/headers', hooks=hooks, headers=headers)224 {225 "headers": {226 "Content-Length": "",227 "Accept-Encoding": "gzip",228 "Yo": "dawg",229 "X-Forwarded-For": "::ffff:24.127.96.129",230 "Connection": "close",231 "User-Agent": "python-requests.org",232 "Host": "httpbin.org",233 "X-Testing": "True",234 "X-Forwarded-Protocol": "",235 "Content-Type": ""236 }237 }238239240Custom Authentication241---------------------242243Requests allows you to use specify your own authentication mechanism.244245Any callable which is passed as the ``auth`` argument to a request method will246have the opportunity to modify the request before it is dispatched.247248Authentication implementations are subclasses of ``requests.auth.AuthBase``,249and are easy to define. Requests provides two common authentication scheme250implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.251252Let's pretend that we have a web service that will only respond if the253``X-Pizza`` header is set to a password value. Unlikely, but just go with it.254255::256257 from requests.auth import AuthBase258 class PizzaAuth(AuthBase):259 """Attaches HTTP Pizza Authentication to the given Request object."""260 def __init__(self, username):261 # setup any auth-related data here262 self.username = username263264 def __call__(self, r):265 # modify and return the request266 r.headers['X-Pizza'] = self.username267 return r268269Then, we can make a request using our Pizza Auth::270271 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))272 <Response [200]>273274Streaming Requests275------------------276277With ``requests.Response.iter_lines()`` you can easily iterate over streaming278APIs such as the `Twitter Streaming API <https://dev.twitter.com/docs/streaming-api>`_.279280To use the Twitter Streaming API to track the keyword "requests"::281282 import requests283 import json284285 r = requests.post('https://stream.twitter.com/1/statuses/filter.json',286 data={'track': 'requests'}, auth=('username', 'password'), prefetch=False)287288 for line in r.iter_lines():289 if line: # filter out keep-alive new lines290 print json.loads(line)291292293Verbose Logging294---------------295296If you want to get a good look at what HTTP requests are being sent297by your application, you can turn on verbose logging.298299To do so, just configure Requests with a stream to write to::300301 >>> my_config = {'verbose': sys.stderr}302 >>> requests.get('http://httpbin.org/headers', config=my_config)303 2011-08-17T03:04:23.380175 GET http://httpbin.org/headers304 <Response [200]>305306307Proxies308-------309310If you need to use a proxy, you can configure individual requests with the311``proxies`` argument to any request method::312313 import requests314315 proxies = {316 "http": "10.10.1.10:3128",317 "https": "10.10.1.10:1080",318 }319320 requests.get("http://example.org", proxies=proxies)321322You can also configure proxies by environment variables ``HTTP_PROXY`` and ``HTTPS_PROXY``.323324::325326 $ export HTTP_PROXY="10.10.1.10:3128"327 $ export HTTPS_PROXY="10.10.1.10:1080"328 $ python329 >>> import requests330 >>> requests.get("http://example.org")331332To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::333334 proxies = {335 "http": "http://user:pass@10.10.1.10:3128/",336 }337338Compliance339----------340341Requests is intended to be compliant with all relevant specifications and342RFCs where that compliance will not cause difficulties for users. This343attention to the specification can lead to some behaviour that may seem344unusual to those not familiar with the relevant specification.345346Encodings347^^^^^^^^^348349When you receive a response, Requests makes a guess at the encoding to use for350decoding the response when you call the ``Response.text`` method. Requests351will first check for an encoding in the HTTP header, and if none is present,352will use `chardet <http://pypi.python.org/pypi/chardet>`_ to attempt to guess353the encoding.354355The only time Requests will not do this is if no explicit charset is present356in the HTTP headers **and** the ``Content-Type`` header contains ``text``. In357this situation,358`RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_359specifies that the default charset must be ``ISO-8859-1``. Requests follows360the specification in this case. If you require a different encoding, you can361manually set the ``Response.encoding`` property, or use the raw362``Response.content``.363364HTTP Verbs365----------366367Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,368HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of369using these various verbs in Requests, using the GitHub API.370371We will begin with the verb most commonly used: GET. HTTP GET is an idempotent372method that returns a resource from a given URL. As a result, it is the verb373you ought to use when attempting to retrieve data from a web location. An374example usage would be attempting to get information about a specific commit375from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it376like so::377378 >>> import requests379 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')380381We should confirm that GitHub responded correctly. If it has, we want to work382out what type of content it is. Do this like so::383384 >>> if (r.status_code == requests.codes.ok):385 ... print r.headers['content-type']386 ...387 application/json; charset=utf-8388389So, GitHub returns JSON. That's great, we can use the JSON module to turn it390into Python objects. Because GitHub returned UTF-8, we should use the391``r.text`` method, not the ``r.content`` method. ``r.content`` returns a392bytestring, while ``r.text`` returns a Unicode-encoded string. I have no plans393to perform byte-manipulation on this response, so I want any Unicode code394points encoded.395396::397398 >>> import json399 >>> commit_data = json.loads(r.text)400 >>> print commit_data.keys()401 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']402 >>> print commit_data[u'committer']403 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}404 >>> print commit_data[u'message']405 makin' history406407So far, so simple. Well, let's investigate the GitHub API a little bit. Now,408we could look at the documentation, but we might have a little more fun if we409use Requests instead. We can take advantage of the Requests OPTIONS verb to410see what kinds of HTTP methods are supported on the url we just used.411412::413414 >>> verbs = requests.options(r.url)415 >>> verbs.status_code416 500417418Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't419actually implement the OPTIONS method. This is an annoying oversight, but it's420OK, we can just use the boring documentation. If GitHub had correctly421implemented OPTIONS, however, they should return the allowed methods in the422headers, e.g.423424::425426 >>> verbs = requests.options('http://a-good-website.com/api/cats')427 >>> print verbs.headers['allow']428 GET,HEAD,POST,OPTIONS429430Turning to the documentation, we see that the only other method allowed for431commits is POST, which creates a new commit. As we're using the Requests repo,432we should probably avoid making ham-handed POSTS to it. Instead, let's play433with the Issues feature of GitHub.434435This documentation was added in response to Issue #482. Given that this issue436already exists, we will use it as an example. Let's start by getting it.437438::439440 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')441 >>> r.status_code442 200443 >>> issue = json.loads(r.text)444 >>> print issue[u'title']445 Feature any http verb in docs446 >>> print issue[u'comments']447 3448449Cool, we have three comments. Let's take a look at the last of them.450451::452453 >>> r = requests.get(r.url + u'/comments')454 >>> r.status_code455 200456 >>> comments = json.loads(r.text)457 >>> print comments[0].keys()458 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']459 >>> print comments[2][u'body']460 Probably in the "advanced" section461462Well, that seems like a silly place. Let's post a comment telling the poster463that he's silly. Who is the poster, anyway?464465::466467 >>> print comments[2][u'user'][u'login']468 kennethreitz469470OK, so let's tell this Kenneth guy that we think this example should go in the471quickstart guide instead. According to the GitHub API doc, the way to do this472is to POST to the thread. Let's do it.473474::475476 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})477 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"478 >>> r = requests.post(url=url, data=body)479 >>> r.status_code480 404481482Huh, that's weird. We probably need to authenticate. That'll be a pain, right?483Wrong. Requests makes it easy to use many forms of authentication, including484the very common Basic Auth.485486::487488 >>> from requests.auth import HTTPBasicAuth489 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')490 >>> r = requests.post(url=url, data=body, auth=auth)491 >>> r.status_code492 201493 >>> content = json.loads(r.text)494 >>> print content[u'body']495 Sounds great! I'll get right on it.496497Brilliant. Oh, wait, no! I meant to add that it would take me a while, because498I had to go feed my cat. If only I could edit this comment! Happily, GitHub499allows us to use another HTTP verb, PATCH, to edit this comment. Let's do500that.501502::503504 >>> print content[u"id"]505 5804413506 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})507 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"508 >>> r = requests.patch(url=url, data=body, auth=auth)509 >>> r.status_code510 200511512Excellent. Now, just to torture this Kenneth guy, I've decided to let him513sweat and not tell him that I'm working on this. That means I want to delete514this comment. GitHub lets us delete comments using the incredibly aptly named515DELETE method. Let's get rid of it.516517::518519 >>> r = requests.delete(url=url, auth=auth)520 >>> r.status_code521 204522 >>> r.headers['status']523 '204 No Content'524525Excellent. All gone. The last thing I want to know is how much of my ratelimit526I've used. Let's find out. GitHub sends that information in the headers, so527rather than download the whole page I'll send a HEAD request to get the528headers.529530::531532 >>> r = requests.head(url=url, auth=auth)533 >>> print r.headers534 ...535 'x-ratelimit-remaining': '4995'536 'x-ratelimit-limit': '5000'537 ...538539Excellent. Time to write a Python program that abuses the GitHub API in all540kinds of exciting ways, 4995 more times.541542Link Headers543------------544545Many HTTP APIs feature Link headers. They make APIs more self describing and discoverable.546547GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_ in their API, for example::548549 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'550 >>> r = requests.head(url=url)551 >>> r.headers['link']552 '<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"'553554Requests will automatically parse these link headers and make them easily consumable::555556 >>> r.links['next']557 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10'558559 >>> r.links['last']560 'https://api.github.com/users/kennethreitz/repos?page=6&per_page=10'561