advanced.rst
This file
Path
docs/user/advanced.rst
940 lines · 32.2 KiB
Last changed by
Merge pull request #3173 from Lukasa/socks-proxy-docsIan Cordascobefore adoption3669b42
History of this fileTake it
The walk stopped after 200 commits: lines older than 3cf4ec4 point at it.
Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 1–26why, one step back1.. _advanced:23Advanced Usage4==============56This document covers some of Requests more advanced features.78.. _session-objects:910Session Objects11---------------1213The Session object allows you to persist certain parameters across14requests. It also persists cookies across all requests made from the15Session instance, and will use ``urllib3``'s `connection pooling`_. So if16you're making several requests to the same host, the underlying TCP17connection will be reused, which can result in a significant performance18increase (see `HTTP persistent connection`_).1920A Session object has all the methods of the main Requests API.2122Let's persist some cookies across requests::2324 s = requests.Session()2526 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 27why, one step back27 r = s.get('http://httpbin.org/cookies')Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 28–52why, one step back2829 print(r.text)30 # '{"cookies": {"sessioncookie": "123456789"}}'313233Sessions can also be used to provide default data to the request methods. This34is done by providing data to the properties on a Session object::3536 s = requests.Session()37 s.auth = ('user', 'pass')38 s.headers.update({'x-test': 'true'})3940 # both 'x-test' and 'x-test2' are sent41 s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})424344Any dictionaries that you pass to a request method will be merged with the45session-level values that are set. The method-level parameters override session46parameters.4748Note, however, that method-level parameters will *not* be persisted across49requests, even if using a session. This example will only send the cookies50with the first request, but not the second::5152 s = requests.Session()cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 53why, one step back53Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 54–72why, one step back54 r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'5758 r = s.get('http://httpbin.org/cookies')59 print(r.text)60 # '{"cookies": {}}'616263If you want to manually add cookies to your session, use the64:ref:`Cookie utility functions <api-cookies>` to manipulate65:attr:`Session.cookies <requests.Session.cookies>`.6667Sessions can also be used as context managers::6869 with requests.Session() as s:70 s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')7172This will make sure the session is closed as soon as the ``with`` block isMerge pull request #2769 from jwilk/spellingCory Benfieldbefore adoption17a9e6d
line 73why, one step back73exited, even if unhandled exceptions occurred.Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 74–132why, one step back747576.. admonition:: Remove a Value From a Dict Parameter7778 Sometimes you'll want to omit session-level keys from a dict parameter. To79 do this, you simply set that key's value to ``None`` in the method-level80 parameter. It will automatically be omitted.8182All values that are contained within a session are directly available to you.83See the :ref:`Session API Docs <sessionapi>` to learn more.8485.. _request-and-response-objects:8687Request and Response Objects88----------------------------8990Whenever a call is made to ``requests.get()`` and friends you are doing two91major things. First, you are constructing a ``Request`` object which will be92sent off to a server to request or query some resource. Second, a ``Response``93object is generated once ``requests`` gets a response back from the server.94The Response object contains all of the information returned by the server and95also contains the ``Request`` object you created originally. Here is a simple96request to get some very important information from Wikipedia's servers::9798 >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')99100If we want to access the headers the server sent back to us, we do this::101102 >>> r.headers103 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':104 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':105 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',106 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',107 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,108 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':109 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,110 MISS from cp1010.eqiad.wmnet:80'}111112However, if we want to get the headers we sent the server, we simply access the113request, and then the request's headers::114115 >>> r.request.headers116 {'Accept-Encoding': 'identity, deflate, compress, gzip',117 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}118119.. _prepared-requests:120121Prepared Requests122-----------------123124Whenever you receive a :class:`Response <requests.Response>` object125from an API call or a Session call, the ``request`` attribute is actually the126``PreparedRequest`` that was used. In some cases you may wish to do some extra127work to the body or headers (or anything else really) before sending a128request. The simple recipe for this is the following::129130 from requests import Request, Session131132 s = Session()cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
lines 133–134why, one step back133134 req = Request('POST', url, data=data, headers=headers)Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 135–137why, one step back135 prepped = req.prepare()136137 # do something with prepped.bodycleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
lines 138–139why, one step back138 prepped.body = 'No, I want exactly this as the body.'139Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 140why, one step back140 # do something with prepped.headerscleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 141why, one step back141 del prepped.headers['Content-Type']Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 142–169why, one step back142143 resp = s.send(prepped,144 stream=stream,145 verify=verify,146 proxies=proxies,147 cert=cert,148 timeout=timeout149 )150151 print(resp.status_code)152153Since you are not doing anything special with the ``Request`` object, you154prepare it immediately and modify the ``PreparedRequest`` object. You then155send that with the other parameters you would have sent to ``requests.*`` or156``Session.*``.157158However, the above code will lose some of the advantages of having a Requests159:class:`Session <requests.Session>` object. In particular,160:class:`Session <requests.Session>`-level state such as cookies will161not get applied to your request. To get a162:class:`PreparedRequest <requests.PreparedRequest>` with that state163applied, replace the call to :meth:`Request.prepare()164<requests.Request.prepare>` with a call to165:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::166167 from requests import Request, Session168169 s = Session()improve advanced.rstKenneth Reitzbefore adoptionf4445b3
line 170why, one step back170 req = Request('GET', url, data=data, headers=headers)Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 171–174why, one step back171172 prepped = s.prepare_request(req)173174 # do something with prepped.bodyimprove advanced.rstKenneth Reitzbefore adoptionf4445b3
lines 175–176why, one step back175 prepped.body = 'Seriously, send exactly these bytes.'176Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 177why, one step back177 # do something with prepped.headersimprove advanced.rstKenneth Reitzbefore adoptionf4445b3
line 178why, one step back178 prepped.headers['Keep-Dead'] = 'parrot'Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 179–194why, one step back179180 resp = s.send(prepped,181 stream=stream,182 verify=verify,183 proxies=proxies,184 cert=cert,185 timeout=timeout186 )187188 print(resp.status_code)189190.. _verification:191192SSL Cert Verification193---------------------194Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414
lines 195–197why, one step back195Requests verifies SSL certificates for HTTPS requests, just like a web browser.196By default, SSL verification is enabled, and requests will throw a SSLError if197it's unable to verify the certificate::Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 198why, one step back198Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414
lines 199–200why, one step back199 >>> requests.get('https://requestb.in')200 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 201why, one step back201Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414
line 202why, one step back202I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 203why, one step back203Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414
line 204why, one step back204 >>> requests.get('https://github.com')Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 205–206why, one step back205 <Response [200]>206Merge pull request #2858 from Lukasa/support_ca_cert_directoriesIan Cordascobefore adoption35170e1
line 207why, one step back207You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::Merge pull request #2753 from Lukasa/ssldocsIan Cordascobefore adoption719c76c
lines 208–210why, one step back208209 >>> requests.get('https://github.com', verify='/path/to/certfile')210Merge pull request #3171 from luv/masterCory Benfieldbefore adoption989e8f1
lines 211–213why, one step back211.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using 212 the c_rehash utility supplied with OpenSSL.213Merge pull request #2753 from Lukasa/ssldocsIan Cordascobefore adoption719c76c
line 214why, one step back214This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 215–228why, one step back215216Requests can also ignore verifying the SSL certificate if you set ``verify`` to False.217218::219220 >>> requests.get('https://kennethreitz.com', verify=False)221 <Response [200]>222223By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.224225You can also specify a local cert to use as client side certificate, as a single226file (containing the private key and the certificate) or as a tuple of both227file's path::228Merge pull request #2948 from vincentbernat/patch-1Cory Benfieldbefore adoptioncbb0830
line 229why, one step back229 >>> requests.get('https://kennethreitz.com', cert=('/path/client.cert', '/path/client.key'))Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 230–231why, one step back230 <Response [200]>231Merge pull request #3057 from kevinburke/secure-by-defaultCory Benfieldbefore adoptionc9f8414
line 232why, one step back232If you specify a wrong path or an invalid cert, you'll get a SSLError::Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 233why, one step back233Merge pull request #2948 from vincentbernat/patch-1Cory Benfieldbefore adoptioncbb0830
line 234why, one step back234 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/client.pem')Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 235–236why, one step back235 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib236Merge pull request #2981 from Lukasa/unencrypted-keysIan Cordascobefore adoption645ac30
lines 237–239why, one step back237.. warning:: The private key to your local certificate *must* be unencrypted.238 Currently, requests does not support using encrypted keys.239Merge pull request #2772 from jimbrowne/masterCory Benfieldbefore adoption7c74050
lines 240–257why, one step back240.. _ca-certificates:241242CA Certificates243---------------244245By default Requests bundles a set of root CAs that it trusts, sourced from the246`Mozilla trust store`_. However, these are only updated once for each Requests247version. This means that if you pin a Requests version your certificates can248become extremely out of date.249250From Requests version 2.4.0 onwards, Requests will attempt to use certificates251from `certifi`_ if it is present on the system. This allows for users to update252their trusted certificates without having to change the code that runs on their253system.254255For the sake of security we recommend upgrading certifi frequently!256257.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connectionMerge pull request #3136 from Natim/readthedocs.ioCory Benfieldbefore adoption252bfa7
line 258why, one step back258.. _connection pooling: https://urllib3.readthedocs.io/en/latest/pools.htmlMerge pull request #2772 from jimbrowne/masterCory Benfieldbefore adoption7c74050
lines 259–261why, one step back259.. _certifi: http://certifi.io/260.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt261Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 262–326why, one step back262.. _body-content-workflow:263264Body Content Workflow265---------------------266267By default, when you make a request, the body of the response is downloaded268immediately. You can override this behaviour and defer downloading the response269body until you access the :class:`Response.content <requests.Response.content>`270attribute with the ``stream`` parameter::271272 tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'273 r = requests.get(tarball_url, stream=True)274275At this point only the response headers have been downloaded and the connection276remains open, hence allowing us to make content retrieval conditional::277278 if int(r.headers['content-length']) < TOO_LONG:279 content = r.content280 ...281282You can further control the workflow by use of the :class:`Response.iter_content <requests.Response.iter_content>`283and :class:`Response.iter_lines <requests.Response.iter_lines>` methods.284Alternatively, you can read the undecoded body from the underlying285urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at286:class:`Response.raw <requests.Response.raw>`.287288If you set ``stream`` to ``True`` when making a request, Requests cannot289release the connection back to the pool unless you consume all the data or call290:class:`Response.close <requests.Response.close>`. This can lead to291inefficiency with connections. If you find yourself partially reading request292bodies (or not reading them at all) while using ``stream=True``, you should293consider using ``contextlib.closing`` (`documented here`_), like this::294295 from contextlib import closing296297 with closing(requests.get('http://httpbin.org/get', stream=True)) as r:298 # Do things with the response here.299300.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing301302.. _keep-alive:303304Keep-Alive305----------306307Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!308Any requests that you make within a session will automatically reuse the appropriate309connection!310311Note that connections are only released back to the pool for reuse once all body312data has been read; be sure to either set ``stream`` to ``False`` or read the313``content`` property of the ``Response`` object.314315.. _streaming-uploads:316317Streaming Uploads318-----------------319320Requests supports streaming uploads, which allow you to send large streams or321files without reading them into memory. To stream and upload, simply provide a322file-like object for your body::323324 with open('massive-body', 'rb') as f:325 requests.post('http://some.url/streamed', data=f)326Merge pull request #2825 from Lukasa/universal_newlinesIan Cordascobefore adoptiond290a9b
lines 327–335why, one step back327.. warning:: It is strongly recommended that you open files in `binary mode`_.328 This is because Requests may attempt to provide the329 ``Content-Length`` header for you, and if it does this value will330 be set to the number of *bytes* in the file. Errors may occur if331 you open the file in *text mode*.332333.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files334335Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 336–364why, one step back336.. _chunk-encoding:337338Chunk-Encoded Requests339----------------------340341Requests also supports Chunked transfer encoding for outgoing and incoming requests.342To send a chunk-encoded request, simply provide a generator (or any iterator without343a length) for your body::344345 def gen():346 yield 'hi'347 yield 'there'348349 requests.post('http://some.url/chunked', data=gen())350351For chunked encoded responses, it's best to iterate over the data using352:meth:`Response.iter_content() <requests.models.Response.iter_content>`. In353an ideal situation you'll have set ``stream=True`` on the request, in which354case you can iterate chunk-by-chunk by calling ``iter_content`` with a chunk355size parameter of ``None``. If you want to set a maximum size of the chunk,356you can set a chunk size parameter to any integer.357358359.. _multipart:360361POST Multiple Multipart-Encoded Files362-------------------------------------363364You can send multiple files in one request. For example, suppose you want todocs cleanupKenneth Reitzbefore adoptione98d71d
line 365why, one step back365upload image files to an HTML form with a multiple file field 'images'::Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 366–368why, one step back366367 <input type="file" name="images" multiple="true" required="true"/>368improve advanced.rstKenneth Reitzbefore adoptionf4445b3
line 369why, one step back369To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 370–371why, one step back370371 >>> url = 'http://httpbin.org/post'improve advanced.rstKenneth Reitzbefore adoptionf4445b3
lines 372–374why, one step back372 >>> multiple_files = [373 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),374 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 375–383why, one step back375 >>> r = requests.post(url, files=multiple_files)376 >>> r.text377 {378 ...379 'files': {'images': 'data:image/png;base64,iVBORw ....'}380 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',381 ...382 }383Merge pull request #2825 from Lukasa/universal_newlinesIan Cordascobefore adoptiond290a9b
lines 384–392why, one step back384.. warning:: It is strongly recommended that you open files in `binary mode`_.385 This is because Requests may attempt to provide the386 ``Content-Length`` header for you, and if it does this value will387 be set to the number of *bytes* in the file. Errors may occur if388 you open the file in *text mode*.389390.. _binary mode: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files391392Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 393–500why, one step back393.. _event-hooks:394395Event Hooks396-----------397398Requests has a hook system that you can use to manipulate portions of399the request process, or signal event handling.400401Available hooks:402403``response``:404 The response generated from a Request.405406407You can assign a hook function on a per-request basis by passing a408``{hook_name: callback_function}`` dictionary to the ``hooks`` request409parameter::410411 hooks=dict(response=print_url)412413That ``callback_function`` will receive a chunk of data as its first414argument.415416::417418 def print_url(r, *args, **kwargs):419 print(r.url)420421If an error occurs while executing your callback, a warning is given.422423If the callback function returns a value, it is assumed that it is to424replace the data that was passed in. If the function doesn't return425anything, nothing else is effected.426427Let's print some request method arguments at runtime::428429 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))430 http://httpbin.org431 <Response [200]>432433.. _custom-auth:434435Custom Authentication436---------------------437438Requests allows you to use specify your own authentication mechanism.439440Any callable which is passed as the ``auth`` argument to a request method will441have the opportunity to modify the request before it is dispatched.442443Authentication implementations are subclasses of ``requests.auth.AuthBase``,444and are easy to define. Requests provides two common authentication scheme445implementations in ``requests.auth``: ``HTTPBasicAuth`` and ``HTTPDigestAuth``.446447Let's pretend that we have a web service that will only respond if the448``X-Pizza`` header is set to a password value. Unlikely, but just go with it.449450::451452 from requests.auth import AuthBase453454 class PizzaAuth(AuthBase):455 """Attaches HTTP Pizza Authentication to the given Request object."""456 def __init__(self, username):457 # setup any auth-related data here458 self.username = username459460 def __call__(self, r):461 # modify and return the request462 r.headers['X-Pizza'] = self.username463 return r464465Then, we can make a request using our Pizza Auth::466467 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))468 <Response [200]>469470.. _streaming-requests:471472Streaming Requests473------------------474475With :class:`requests.Response.iter_lines()` you can easily476iterate over streaming APIs such as the `Twitter Streaming477API <https://dev.twitter.com/streaming/overview>`_. Simply478set ``stream`` to ``True`` and iterate over the response with479:class:`~requests.Response.iter_lines()`::480481 import json482 import requests483484 r = requests.get('http://httpbin.org/stream/20', stream=True)485486 for line in r.iter_lines():487488 # filter out keep-alive new lines489 if line:490 print(json.loads(line))491492.. warning::493494 :class:`~requests.Response.iter_lines()` is not reentrant safe.495 Calling this method multiple times causes some of the received data496 being lost. In case you need to call it from multiple places, use497 the resulting iterator object instead::498499 lines = r.iter_lines()500 # Save the first line for later or just skip itcleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 501why, one step back501Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 502why, one step back502 first_line = next(lines)cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 503why, one step back503Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 504–517why, one step back504 for line in lines:505 print(line)506507.. _proxies:508509Proxies510-------511512If you need to use a proxy, you can configure individual requests with the513``proxies`` argument to any request method::514515 import requests516517 proxies = {cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
lines 518–519why, one step back518 'http': 'http://10.10.1.10:3128',519 'https': 'http://10.10.1.10:1080',Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 520–521why, one step back520 }521cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 522why, one step back522 requests.get('http://example.org', proxies=proxies)Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 523–530why, one step back523524You can also configure proxies by setting the environment variables525``HTTP_PROXY`` and ``HTTPS_PROXY``.526527::528529 $ export HTTP_PROXY="http://10.10.1.10:3128"530 $ export HTTPS_PROXY="http://10.10.1.10:1080"docs cleanupKenneth Reitzbefore adoptione98d71d
line 531why, one step back531Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 532–533why, one step back532 $ python533 >>> import requestscleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 534why, one step back534 >>> requests.get('http://example.org')Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 535–537why, one step back535536To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::537improve further advanced.rstKenneth Reitzbefore adoptionf8af499
line 538why, one step back538 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 539why, one step back539Merge pull request #2741 from jasongrout/per-host-proxyCory Benfieldbefore adoption56ecdeb
lines 540–542why, one step back540To give a proxy for a specific scheme and host, use the541`scheme://hostname` form for the key. This will match for542any request to the given scheme and exact hostname.Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 543why, one step back543Merge pull request #2741 from jasongrout/per-host-proxyCory Benfieldbefore adoption56ecdeb
lines 544–545why, one step back544::545improve further advanced.rstKenneth Reitzbefore adoptionf8af499
line 546why, one step back546 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}Merge pull request #2741 from jasongrout/per-host-proxyCory Benfieldbefore adoption56ecdeb
lines 547–548why, one step back547548Note that proxy URLs must include the scheme.Merge pull request #2825 from Lukasa/universal_newlinesIan Cordascobefore adoptiond290a9b
line 549why, one step back549Merge pull request #3173 from Lukasa/socks-proxy-docsIan Cordascobefore adoption3669b42
lines 550–572why, one step back550SOCKS551^^^^^552553.. versionadded:: 2.10.0554555In addition to basic HTTP proxies, requests also supports proxies using the556SOCKS protocol. This is an optional feature that requires that additional557third-party libraries be installed before use.558559You can get the dependencies for this feature from ``pip``:560561.. code-block:: bash562563 $ pip install requests[socks]564565Once you've installed those dependencies, using a SOCKS proxy is just as easy566as using a HTTP one::567568 proxies = {569 'http': 'socks5://user:pass@host:port',570 'https': 'socks5://user:pass@host:port'571 }572Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 573–633why, one step back573.. _compliance:574575Compliance576----------577578Requests is intended to be compliant with all relevant specifications and579RFCs where that compliance will not cause difficulties for users. This580attention to the specification can lead to some behaviour that may seem581unusual to those not familiar with the relevant specification.582583Encodings584^^^^^^^^^585586When you receive a response, Requests makes a guess at the encoding to587use for decoding the response when you access the :attr:`Response.text588<requests.Response.text>` attribute. Requests will first check for an589encoding in the HTTP header, and if none is present, will use `chardet590<http://pypi.python.org/pypi/chardet>`_ to attempt to guess the encoding.591592The only time Requests will not do this is if no explicit charset593is present in the HTTP headers **and** the ``Content-Type``594header contains ``text``. In this situation, `RFC 2616595<http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies596that the default charset must be ``ISO-8859-1``. Requests follows the597specification in this case. If you require a different encoding, you can598manually set the :attr:`Response.encoding <requests.Response.encoding>`599property, or use the raw :attr:`Response.content <requests.Response.content>`.600601.. _http-verbs:602603HTTP Verbs604----------605606Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,607HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of608using these various verbs in Requests, using the GitHub API.609610We will begin with the verb most commonly used: GET. HTTP GET is an idempotent611method that returns a resource from a given URL. As a result, it is the verb612you ought to use when attempting to retrieve data from a web location. An613example usage would be attempting to get information about a specific commit614from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it615like so::616617 >>> import requests618 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')619620We should confirm that GitHub responded correctly. If it has, we want to work621out what type of content it is. Do this like so::622623 >>> if r.status_code == requests.codes.ok:624 ... print(r.headers['content-type'])625 ...626 application/json; charset=utf-8627628So, GitHub returns JSON. That's great, we can use the :meth:`r.json629<requests.Response.json>` method to parse it into Python objects.630631::632633 >>> commit_data = r.json()cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 634why, one step back634Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 635–636why, one step back635 >>> print(commit_data.keys())636 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 637why, one step back637Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 638–639why, one step back638 >>> print(commit_data[u'committer'])639 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 640why, one step back640Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 641–679why, one step back641 >>> print(commit_data[u'message'])642 makin' history643644So far, so simple. Well, let's investigate the GitHub API a little bit. Now,645we could look at the documentation, but we might have a little more fun if we646use Requests instead. We can take advantage of the Requests OPTIONS verb to647see what kinds of HTTP methods are supported on the url we just used.648649::650651 >>> verbs = requests.options(r.url)652 >>> verbs.status_code653 500654655Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't656actually implement the OPTIONS method. This is an annoying oversight, but it's657OK, we can just use the boring documentation. If GitHub had correctly658implemented OPTIONS, however, they should return the allowed methods in the659headers, e.g.660661::662663 >>> verbs = requests.options('http://a-good-website.com/api/cats')664 >>> print(verbs.headers['allow'])665 GET,HEAD,POST,OPTIONS666667Turning to the documentation, we see that the only other method allowed for668commits is POST, which creates a new commit. As we're using the Requests repo,669we should probably avoid making ham-handed POSTS to it. Instead, let's play670with the Issues feature of GitHub.671672This documentation was added in response to Issue #482. Given that this issue673already exists, we will use it as an example. Let's start by getting it.674675::676677 >>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/issues/482')678 >>> r.status_code679 200cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 680why, one step back680Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 681why, one step back681 >>> issue = json.loads(r.text)cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 682why, one step back682Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 683–684why, one step back683 >>> print(issue[u'title'])684 Feature any http verb in docscleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 685why, one step back685Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 686–695why, one step back686 >>> print(issue[u'comments'])687 3688689Cool, we have three comments. Let's take a look at the last of them.690691::692693 >>> r = requests.get(r.url + u'/comments')694 >>> r.status_code695 200cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 696why, one step back696Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
line 697why, one step back697 >>> comments = r.json()cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 698why, one step back698Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 699–700why, one step back699 >>> print(comments[0].keys())700 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 701why, one step back701Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 702–720why, one step back702 >>> print(comments[2][u'body'])703 Probably in the "advanced" section704705Well, that seems like a silly place. Let's post a comment telling the poster706that he's silly. Who is the poster, anyway?707708::709710 >>> print(comments[2][u'user'][u'login'])711 kennethreitz712713OK, so let's tell this Kenneth guy that we think this example should go in the714quickstart guide instead. According to the GitHub API doc, the way to do this715is to POST to the thread. Let's do it.716717::718719 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})720 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/482/comments"cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 721why, one step back721Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 722–733why, one step back722 >>> r = requests.post(url=url, data=body)723 >>> r.status_code724 404725726Huh, that's weird. We probably need to authenticate. That'll be a pain, right?727Wrong. Requests makes it easy to use many forms of authentication, including728the very common Basic Auth.729730::731732 >>> from requests.auth import HTTPBasicAuth733 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 734why, one step back734Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 735–737why, one step back735 >>> r = requests.post(url=url, data=body, auth=auth)736 >>> r.status_code737 201cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 738why, one step back738Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 739–751why, one step back739 >>> content = r.json()740 >>> print(content[u'body'])741 Sounds great! I'll get right on it.742743Brilliant. Oh, wait, no! I meant to add that it would take me a while, because744I had to go feed my cat. If only I could edit this comment! Happily, GitHub745allows us to use another HTTP verb, PATCH, to edit this comment. Let's do746that.747748::749750 >>> print(content[u"id"])751 5804413cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 752why, one step back752Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 753–754why, one step back753 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})754 >>> url = u"https://api.github.com/repos/kennethreitz/requests/issues/comments/5804413"cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
line 755why, one step back755Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 756–875why, one step back756 >>> r = requests.patch(url=url, data=body, auth=auth)757 >>> r.status_code758 200759760Excellent. Now, just to torture this Kenneth guy, I've decided to let him761sweat and not tell him that I'm working on this. That means I want to delete762this comment. GitHub lets us delete comments using the incredibly aptly named763DELETE method. Let's get rid of it.764765::766767 >>> r = requests.delete(url=url, auth=auth)768 >>> r.status_code769 204770 >>> r.headers['status']771 '204 No Content'772773Excellent. All gone. The last thing I want to know is how much of my ratelimit774I've used. Let's find out. GitHub sends that information in the headers, so775rather than download the whole page I'll send a HEAD request to get the776headers.777778::779780 >>> r = requests.head(url=url, auth=auth)781 >>> print(r.headers)782 ...783 'x-ratelimit-remaining': '4995'784 'x-ratelimit-limit': '5000'785 ...786787Excellent. Time to write a Python program that abuses the GitHub API in all788kinds of exciting ways, 4995 more times.789790.. _link-headers:791792Link Headers793------------794795Many HTTP APIs feature Link headers. They make APIs more self describing and796discoverable.797798GitHub uses these for `pagination <http://developer.github.com/v3/#pagination>`_799in their API, for example::800801 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'802 >>> r = requests.head(url=url)803 >>> r.headers['link']804 '<https://api.github.com/users/kennethreitz/repos?page=2&per_page=10>; rel="next", <https://api.github.com/users/kennethreitz/repos?page=6&per_page=10>; rel="last"'805806Requests will automatically parse these link headers and make them easily consumable::807808 >>> r.links["next"]809 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}810811 >>> r.links["last"]812 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}813814.. _transport-adapters:815816Transport Adapters817------------------818819As of v1.0.0, Requests has moved to a modular internal design. Part of the820reason this was done was to implement Transport Adapters, originally821`described here`_. Transport Adapters provide a mechanism to define interaction822methods for an HTTP service. In particular, they allow you to apply per-service823configuration.824825Requests ships with a single Transport Adapter, the :class:`HTTPAdapter826<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests827interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever828a Requests :class:`Session <requests.Session>` is initialized, one of these is829attached to the :class:`Session <requests.Session>` object for HTTP, and one830for HTTPS.831832Requests enables users to create and use their own Transport Adapters that833provide specific functionality. Once created, a Transport Adapter can be834mounted to a Session object, along with an indication of which web services835it should apply to.836837::838839 >>> s = requests.Session()840 >>> s.mount('http://www.github.com', MyAdapter())841842The mount call registers a specific instance of a Transport Adapter to a843prefix. Once mounted, any HTTP request made using that session whose URL starts844with the given prefix will use the given Transport Adapter.845846Many of the details of implementing a Transport Adapter are beyond the scope of847this documentation, but take a look at the next example for a simple SSL use-848case. For more than that, you might look at subclassing849``requests.adapters.BaseAdapter``.850851Example: Specific SSL Version852^^^^^^^^^^^^^^^^^^^^^^^^^^^^^853854The Requests team has made a specific choice to use whatever SSL version is855default in the underlying library (`urllib3`_). Normally this is fine, but from856time to time, you might find yourself needing to connect to a service-endpoint857that uses a version that isn't compatible with the default.858859You can use Transport Adapters for this by taking most of the existing860implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets861passed-through to `urllib3`. We'll make a TA that instructs the library to use862SSLv3:863864::865866 import ssl867868 from requests.adapters import HTTPAdapter869 from requests.packages.urllib3.poolmanager import PoolManager870871872 class Ssl3HttpAdapter(HTTPAdapter):873 """"Transport adapter" that allows us to use SSLv3."""874875 def init_poolmanager(self, connections, maxsize, block=False):cleanup advanced.rstKenneth Reitzbefore adoptionf4f863f
lines 876–878why, one step back876 self.poolmanager = PoolManager(877 num_pools=connections, maxsize=maxsize,878 block=block, ssl_version=ssl.PROTOCOL_SSLv3)Merge pull request #2729 from smiley/patch-1Cory Benfieldbefore adoption3cf4ec4
lines 879–940why, one step back879880.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http881.. _`urllib3`: https://github.com/shazow/urllib3882883.. _blocking-or-nonblocking:884885Blocking Or Non-Blocking?886-------------------------887888With the default Transport Adapter in place, Requests does not provide any kind889of non-blocking IO. The :attr:`Response.content <requests.Response.content>`890property will block until the entire response has been downloaded. If891you require more granularity, the streaming features of the library (see892:ref:`streaming-requests`) allow you to retrieve smaller quantities of the893response at a time. However, these calls will still block.894895If you are concerned about the use of blocking IO, there are lots of projects896out there that combine Requests with one of Python's asynchronicity frameworks.897Two excellent examples are `grequests`_ and `requests-futures`_.898899.. _`grequests`: https://github.com/kennethreitz/grequests900.. _`requests-futures`: https://github.com/ross/requests-futures901902.. _timeouts:903904Timeouts905--------906907Most requests to external servers should have a timeout attached, in case the908server is not responding in a timely manner. Without a timeout, your code may909hang for minutes or more.910911The **connect** timeout is the number of seconds Requests will wait for your912client to establish a connection to a remote machine (corresponding to the913`connect()`_) call on the socket. It's a good practice to set connect timeouts914to slightly larger than a multiple of 3, which is the default `TCP packet915retransmission window <http://www.hjp.at/doc/rfc/rfc2988.txt>`_.916917Once your client has connected to the server and sent the HTTP request, the918**read** timeout is the number of seconds the client will wait for the server919to send a response. (Specifically, it's the number of seconds that the client920will wait *between* bytes sent from the server. In 99.9% of cases, this is the921time before the server sends the first byte).922923If you specify a single value for the timeout, like this::924925 r = requests.get('https://github.com', timeout=5)926927The timeout value will be applied to both the ``connect`` and the ``read``928timeouts. Specify a tuple if you would like to set the values separately::929930 r = requests.get('https://github.com', timeout=(3.05, 27))931932If the remote server is very slow, you can tell Requests to wait forever for933a response, by passing None as a timeout value and then retrieving a cup of934coffee.935936.. code-block:: python937938 r = requests.get('https://github.com', timeout=None)939940.. _`connect()`: http://linux.die.net/man/2/connect