advanced.rst
This file
Path
docs/user/advanced.rst
1,141 lines · 41.1 KiB
Last changed by
Merge pull request #6583 from EFord36/fix-broken-linksIan Stapleton Cordascobefore adoptionf3f2611
History of this fileTake it
The walk stopped after 200 commits: lines older than 8c211a9 point at it.
Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1–293why, 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('https://httpbin.org/cookies/set/sessioncookie/123456789')27 r = s.get('https://httpbin.org/cookies')2829 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('https://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()5354 r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})55 print(r.text)56 # '{"cookies": {"from-my": "browser"}}'5758 r = s.get('https://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('https://httpbin.org/cookies/set/sessioncookie/123456789')7172This will make sure the session is closed as soon as the ``with`` block is73exited, even if unhandled exceptions occurred.747576.. 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('https://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()133134 req = Request('POST', url, data=data, headers=headers)135 prepped = req.prepare()136137 # do something with prepped.body138 prepped.body = 'No, I want exactly this as the body.'139140 # do something with prepped.headers141 del prepped.headers['Content-Type']142143 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()170 req = Request('GET', url, data=data, headers=headers)171172 prepped = s.prepare_request(req)173174 # do something with prepped.body175 prepped.body = 'Seriously, send exactly these bytes.'176177 # do something with prepped.headers178 prepped.headers['Keep-Dead'] = 'parrot'179180 resp = s.send(prepped,181 stream=stream,182 verify=verify,183 proxies=proxies,184 cert=cert,185 timeout=timeout186 )187188 print(resp.status_code)189190When you are using the prepared request flow, keep in mind that it does not take into account the environment.191This can cause problems if you are using environment variables to change the behaviour of requests.192For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.193As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.194You can get around this behaviour by explicitly merging the environment settings into your session::195196 from requests import Request, Session197198 s = Session()199 req = Request('GET', url)200201 prepped = s.prepare_request(req)202203 # Merge environment settings into session204 settings = s.merge_environment_settings(prepped.url, {}, None, None, None)205 resp = s.send(prepped, **settings)206207 print(resp.status_code)208209.. _verification:210211SSL Cert Verification212---------------------213214Requests verifies SSL certificates for HTTPS requests, just like a web browser.215By default, SSL verification is enabled, and Requests will throw a SSLError if216it's unable to verify the certificate::217218 >>> requests.get('https://requestb.in')219 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'220221I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::222223 >>> requests.get('https://github.com')224 <Response [200]>225226You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::227228 >>> requests.get('https://github.com', verify='/path/to/certfile')229230or persistent::231232 s = requests.Session()233 s.verify = '/path/to/certfile'234235.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using236 the ``c_rehash`` utility supplied with OpenSSL.237238This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.239If ``REQUESTS_CA_BUNDLE`` is not set, ``CURL_CA_BUNDLE`` will be used as fallback.240241Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::242243 >>> requests.get('https://kennethreitz.org', verify=False)244 <Response [200]>245246Note that when ``verify`` is set to ``False``, requests will accept any TLS247certificate presented by the server, and will ignore hostname mismatches248and/or expired certificates, which will make your application vulnerable to249man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful250during local development or testing.251252By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.253254Client Side Certificates255------------------------256257You can also specify a local cert to use as client side certificate, as a single258file (containing the private key and the certificate) or as a tuple of both259files' paths::260261 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))262 <Response [200]>263264or persistent::265266 s = requests.Session()267 s.cert = '/path/client.cert'268269If you specify a wrong path or an invalid cert, you'll get a SSLError::270271 >>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')272 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib273274.. warning:: The private key to your local certificate *must* be unencrypted.275 Currently, Requests does not support using encrypted keys.276277.. _ca-certificates:278279CA Certificates280---------------281282Requests uses certificates from the package `certifi`_. This allows for users283to update their trusted certificates without changing the version of Requests.284285Before version 2.16, Requests bundled a set of root CAs that it trusted,286sourced from the `Mozilla trust store`_. The certificates were only updated287once for each Requests version. When ``certifi`` was not installed, this led to288extremely out-of-date certificate bundles when using significantly older289versions of Requests.290291For the sake of security we recommend upgrading certifi frequently!292293.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connectionMerge pull request #6583 from EFord36/fix-broken-linksIan Stapleton Cordascobefore adoptionf3f2611
line 294why, one step back294.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.htmlMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 295–307why, one step back295.. _certifi: https://certifiio.readthedocs.io/296.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt297298.. _body-content-workflow:299300Body Content Workflow301---------------------302303By default, when you make a request, the body of the response is downloaded304immediately. You can override this behaviour and defer downloading the response305body until you access the :attr:`Response.content <requests.Response.content>`306attribute with the ``stream`` parameter::307General doc updates (#5923)Nate Prewittbefore adoption9572d6a
line 308why, one step back308 tarball_url = 'https://github.com/psf/requests/tarball/main'Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 309–448why, one step back309 r = requests.get(tarball_url, stream=True)310311At this point only the response headers have been downloaded and the connection312remains open, hence allowing us to make content retrieval conditional::313314 if int(r.headers['content-length']) < TOO_LONG:315 content = r.content316 ...317318You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`319and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.320Alternatively, you can read the undecoded body from the underlying321urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at322:attr:`Response.raw <requests.Response.raw>`.323324If you set ``stream`` to ``True`` when making a request, Requests cannot325release the connection back to the pool unless you consume all the data or call326:meth:`Response.close <requests.Response.close>`. This can lead to327inefficiency with connections. If you find yourself partially reading request328bodies (or not reading them at all) while using ``stream=True``, you should329make the request within a ``with`` statement to ensure it's always closed::330331 with requests.get('https://httpbin.org/get', stream=True) as r:332 # Do things with the response here.333334.. _keep-alive:335336Keep-Alive337----------338339Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!340Any requests that you make within a session will automatically reuse the appropriate341connection!342343Note that connections are only released back to the pool for reuse once all body344data has been read; be sure to either set ``stream`` to ``False`` or read the345``content`` property of the ``Response`` object.346347.. _streaming-uploads:348349Streaming Uploads350-----------------351352Requests supports streaming uploads, which allow you to send large streams or353files without reading them into memory. To stream and upload, simply provide a354file-like object for your body::355356 with open('massive-body', 'rb') as f:357 requests.post('http://some.url/streamed', data=f)358359.. warning:: It is strongly recommended that you open files in :ref:`binary360 mode <tut-files>`. This is because Requests may attempt to provide361 the ``Content-Length`` header for you, and if it does this value362 will be set to the number of *bytes* in the file. Errors may occur363 if you open the file in *text mode*.364365366.. _chunk-encoding:367368Chunk-Encoded Requests369----------------------370371Requests also supports Chunked transfer encoding for outgoing and incoming requests.372To send a chunk-encoded request, simply provide a generator (or any iterator without373a length) for your body::374375 def gen():376 yield 'hi'377 yield 'there'378379 requests.post('http://some.url/chunked', data=gen())380381For chunked encoded responses, it's best to iterate over the data using382:meth:`Response.iter_content() <requests.Response.iter_content>`. In383an ideal situation you'll have set ``stream=True`` on the request, in which384case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``385parameter of ``None``. If you want to set a maximum size of the chunk,386you can set a ``chunk_size`` parameter to any integer.387388389.. _multipart:390391POST Multiple Multipart-Encoded Files392-------------------------------------393394You can send multiple files in one request. For example, suppose you want to395upload image files to an HTML form with a multiple file field 'images'::396397 <input type="file" name="images" multiple="true" required="true"/>398399To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::400401 >>> url = 'https://httpbin.org/post'402 >>> multiple_files = [403 ... ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),404 ... ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]405 >>> r = requests.post(url, files=multiple_files)406 >>> r.text407 {408 ...409 'files': {'images': 'data:image/png;base64,iVBORw ....'}410 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',411 ...412 }413414.. warning:: It is strongly recommended that you open files in :ref:`binary415 mode <tut-files>`. This is because Requests may attempt to provide416 the ``Content-Length`` header for you, and if it does this value417 will be set to the number of *bytes* in the file. Errors may occur418 if you open the file in *text mode*.419420421.. _event-hooks:422423Event Hooks424-----------425426Requests has a hook system that you can use to manipulate portions of427the request process, or signal event handling.428429Available hooks:430431``response``:432 The response generated from a Request.433434435You can assign a hook function on a per-request basis by passing a436``{hook_name: callback_function}`` dictionary to the ``hooks`` request437parameter::438439 hooks={'response': print_url}440441That ``callback_function`` will receive a chunk of data as its first442argument.443444::445446 def print_url(r, *args, **kwargs):447 print(r.url)448fix minor typos (#5934)Kevin Kirschebefore adoptionfc106ab
line 449why, one step back449Your callback function must handle its own exceptions. Any unhandled exception won't be passed silently and thus should be handled by the code calling Requests.Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 450–605why, one step back450451If the callback function returns a value, it is assumed that it is to452replace the data that was passed in. If the function doesn't return453anything, nothing else is affected.454455::456457 def record_hook(r, *args, **kwargs):458 r.hook_called = True459 return r460461Let's print some request method arguments at runtime::462463 >>> requests.get('https://httpbin.org/', hooks={'response': print_url})464 https://httpbin.org/465 <Response [200]>466467You can add multiple hooks to a single request. Let's call two hooks at once::468469 >>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})470 >>> r.hook_called471 True472473You can also add hooks to a ``Session`` instance. Any hooks you add will then474be called on every request made to the session. For example::475476 >>> s = requests.Session()477 >>> s.hooks['response'].append(print_url)478 >>> s.get('https://httpbin.org/')479 https://httpbin.org/480 <Response [200]>481482A ``Session`` can have multiple hooks, which will be called in the order483they are added.484485.. _custom-auth:486487Custom Authentication488---------------------489490Requests allows you to specify your own authentication mechanism.491492Any callable which is passed as the ``auth`` argument to a request method will493have the opportunity to modify the request before it is dispatched.494495Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,496and are easy to define. Requests provides two common authentication scheme497implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and498:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.499500Let's pretend that we have a web service that will only respond if the501``X-Pizza`` header is set to a password value. Unlikely, but just go with it.502503::504505 from requests.auth import AuthBase506507 class PizzaAuth(AuthBase):508 """Attaches HTTP Pizza Authentication to the given Request object."""509 def __init__(self, username):510 # setup any auth-related data here511 self.username = username512513 def __call__(self, r):514 # modify and return the request515 r.headers['X-Pizza'] = self.username516 return r517518Then, we can make a request using our Pizza Auth::519520 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))521 <Response [200]>522523.. _streaming-requests:524525Streaming Requests526------------------527528With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily529iterate over streaming APIs such as the `Twitter Streaming530API <https://dev.twitter.com/streaming/overview>`_. Simply531set ``stream`` to ``True`` and iterate over the response with532:meth:`~requests.Response.iter_lines()`::533534 import json535 import requests536537 r = requests.get('https://httpbin.org/stream/20', stream=True)538539 for line in r.iter_lines():540541 # filter out keep-alive new lines542 if line:543 decoded_line = line.decode('utf-8')544 print(json.loads(decoded_line))545546When using `decode_unicode=True` with547:meth:`Response.iter_lines() <requests.Response.iter_lines>` or548:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want549to provide a fallback encoding in the event the server doesn't provide one::550551 r = requests.get('https://httpbin.org/stream/20', stream=True)552553 if r.encoding is None:554 r.encoding = 'utf-8'555556 for line in r.iter_lines(decode_unicode=True):557 if line:558 print(json.loads(line))559560.. warning::561562 :meth:`~requests.Response.iter_lines()` is not reentrant safe.563 Calling this method multiple times causes some of the received data564 being lost. In case you need to call it from multiple places, use565 the resulting iterator object instead::566567 lines = r.iter_lines()568 # Save the first line for later or just skip it569570 first_line = next(lines)571572 for line in lines:573 print(line)574575.. _proxies:576577Proxies578-------579580If you need to use a proxy, you can configure individual requests with the581``proxies`` argument to any request method::582583 import requests584585 proxies = {586 'http': 'http://10.10.1.10:3128',587 'https': 'http://10.10.1.10:1080',588 }589590 requests.get('http://example.org', proxies=proxies)591592Alternatively you can configure it once for an entire593:class:`Session <requests.Session>`::594595 import requests596597 proxies = {598 'http': 'http://10.10.1.10:3128',599 'https': 'http://10.10.1.10:1080',600 }601 session = requests.Session()602 session.proxies.update(proxies)603604 session.get('http://example.org')605Merge pull request #6068 from nateprewitt/sess_prox_warnIan Stapleton Cordascobefore adoption5e74954
lines 606–618why, one step back606.. warning:: Setting ``session.proxies`` may behave differently than expected.607 Values provided will be overwritten by environmental proxies608 (those returned by `urllib.request.getproxies <https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies>`_).609 To ensure the use of proxies in the presence of environmental proxies,610 explicitly specify the ``proxies`` argument on all individual requests as611 initially explained above.612613 See `#2018 <https://github.com/psf/requests/issues/2018>`_ for details.614615When the proxies configuration is not overridden per request as shown above,616Requests relies on the proxy configuration defined by standard617environment variables ``http_proxy``, ``https_proxy``, ``no_proxy``,618and ``all_proxy``. Uppercase variants of these variables are also supported.Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 619–623why, one step back619You can therefore set them to configure Requests (only set the ones relevant620to your needs)::621622 $ export HTTP_PROXY="http://10.10.1.10:3128"623 $ export HTTPS_PROXY="http://10.10.1.10:1080"Merge pull request #5978 from sha016/all-proxy-docsNate Prewittbefore adoption7ae3887
line 624why, one step back624 $ export ALL_PROXY="socks5://10.10.1.10:3434"Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 625–638why, one step back625626 $ python627 >>> import requests628 >>> requests.get('http://example.org')629630To use HTTP Basic Auth with your proxy, use the `http://user:password@host/`631syntax in any of the above configuration entries::632633 $ export HTTPS_PROXY="http://user:pass@10.10.1.10:1080"634635 $ python636 >>> proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}637638.. warning:: Storing sensitive username and password information in anFix typoAndrew M. Whitebefore adoption913880c
line 639why, one step back639 environment variable or a version-controlled file is a security risk and isMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 640–658why, one step back640 highly discouraged.641642To give a proxy for a specific scheme and host, use the643`scheme://hostname` form for the key. This will match for644any request to the given scheme and exact hostname.645646::647648 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}649650Note that proxy URLs must include the scheme.651652Finally, note that using a proxy for https connections typically requires your653local machine to trust the proxy's root certificate. By default the list of654certificates trusted by Requests can be found with::655656 from requests.utils import DEFAULT_CA_BUNDLE_PATH657 print(DEFAULT_CA_BUNDLE_PATH)658Merge pull request #6234 from jaap3/patch-1Ian Stapleton Cordascobefore adoption7104ad4
lines 659–660why, one step back659You override this default certificate bundle by setting the ``REQUESTS_CA_BUNDLE``660(or ``CURL_CA_BUNDLE``) environment variable to another file path::Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
line 661why, one step back661Merge pull request #6234 from jaap3/patch-1Ian Stapleton Cordascobefore adoption7104ad4
line 662why, one step back662 $ export REQUESTS_CA_BUNDLE="/usr/local/myproxy_info/cacert.pem"Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 663–668why, one step back663 $ export https_proxy="http://10.10.1.10:1080"664665 $ python666 >>> import requests667 >>> requests.get('https://example.org')668Merge pull request #6613 from miketheman/add-socks-labelIan Stapleton Cordascobefore adoptionf3f9784
lines 669–670why, one step back669.. _socks:670Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 671–711why, one step back671SOCKS672^^^^^673674.. versionadded:: 2.10.0675676In addition to basic HTTP proxies, Requests also supports proxies using the677SOCKS protocol. This is an optional feature that requires that additional678third-party libraries be installed before use.679680You can get the dependencies for this feature from ``pip``:681682.. code-block:: bash683684 $ python -m pip install requests[socks]685686Once you've installed those dependencies, using a SOCKS proxy is just as easy687as using a HTTP one::688689 proxies = {690 'http': 'socks5://user:pass@host:port',691 'https': 'socks5://user:pass@host:port'692 }693694Using the scheme ``socks5`` causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use ``socks5h`` as the scheme.695696.. _compliance:697698Compliance699----------700701Requests is intended to be compliant with all relevant specifications and702RFCs where that compliance will not cause difficulties for users. This703attention to the specification can lead to some behaviour that may seem704unusual to those not familiar with the relevant specification.705706Encodings707^^^^^^^^^708709When you receive a response, Requests makes a guess at the encoding to710use for decoding the response when you access the :attr:`Response.text711<requests.Response.text>` attribute. Requests will first check for anSwitch LGPL'd chardet for MIT licensed charset_normalizer (#5797)Ash Berlin-Taylorbefore adoption2ed84f5
lines 712–715why, one step back712encoding in the HTTP header, and if none is present, will use713`charset_normalizer <https://pypi.org/project/charset_normalizer/>`_714or `chardet <https://github.com/chardet/chardet>`_ to attempt to715guess the encoding.Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
line 716why, one step back716Switch LGPL'd chardet for MIT licensed charset_normalizer (#5797)Ash Berlin-Taylorbefore adoption2ed84f5
lines 717–721why, one step back717If ``chardet`` is installed, ``requests`` uses it, however for python3718``chardet`` is no longer a mandatory dependency. The ``chardet``719library is an LGPL-licenced dependency and some users of requests720cannot depend on mandatory LGPL-licensed dependencies.721Remove Python 2 mention on `chardet` behavior (#6204)David Cainbefore adoption177dd90
line 722why, one step back722When you install ``requests`` without specifying ``[use_chardet_on_py3]`` extra,Switch LGPL'd chardet for MIT licensed charset_normalizer (#5797)Ash Berlin-Taylorbefore adoption2ed84f5
line 723why, one step back723and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``Remove Python 2 mention on `chardet` behavior (#6204)David Cainbefore adoption177dd90
line 724why, one step back724(MIT-licensed) to guess the encoding.Switch LGPL'd chardet for MIT licensed charset_normalizer (#5797)Ash Berlin-Taylorbefore adoption2ed84f5
lines 725–726why, one step back725726The only time Requests will not guess the encoding is if no explicit charsetMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 727–950why, one step back727is present in the HTTP headers **and** the ``Content-Type``728header contains ``text``. In this situation, `RFC 2616729<https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies730that the default charset must be ``ISO-8859-1``. Requests follows the731specification in this case. If you require a different encoding, you can732manually set the :attr:`Response.encoding <requests.Response.encoding>`733property, or use the raw :attr:`Response.content <requests.Response.content>`.734735.. _http-verbs:736737HTTP Verbs738----------739740Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,741HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of742using these various verbs in Requests, using the GitHub API.743744We will begin with the verb most commonly used: GET. HTTP GET is an idempotent745method that returns a resource from a given URL. As a result, it is the verb746you ought to use when attempting to retrieve data from a web location. An747example usage would be attempting to get information about a specific commit748from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it749like so::750751 >>> import requests752 >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')753754We should confirm that GitHub responded correctly. If it has, we want to work755out what type of content it is. Do this like so::756757 >>> if r.status_code == requests.codes.ok:758 ... print(r.headers['content-type'])759 ...760 application/json; charset=utf-8761762So, GitHub returns JSON. That's great, we can use the :meth:`r.json763<requests.Response.json>` method to parse it into Python objects.764765::766767 >>> commit_data = r.json()768769 >>> print(commit_data.keys())770 ['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message']771772 >>> print(commit_data['committer'])773 {'date': '2012-05-10T11:10:50-07:00', 'email': 'me@kennethreitz.com', 'name': 'Kenneth Reitz'}774775 >>> print(commit_data['message'])776 makin' history777778So far, so simple. Well, let's investigate the GitHub API a little bit. Now,779we could look at the documentation, but we might have a little more fun if we780use Requests instead. We can take advantage of the Requests OPTIONS verb to781see what kinds of HTTP methods are supported on the url we just used.782783::784785 >>> verbs = requests.options(r.url)786 >>> verbs.status_code787 500788789Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't790actually implement the OPTIONS method. This is an annoying oversight, but it's791OK, we can just use the boring documentation. If GitHub had correctly792implemented OPTIONS, however, they should return the allowed methods in the793headers, e.g.794795::796797 >>> verbs = requests.options('http://a-good-website.com/api/cats')798 >>> print(verbs.headers['allow'])799 GET,HEAD,POST,OPTIONS800801Turning to the documentation, we see that the only other method allowed for802commits is POST, which creates a new commit. As we're using the Requests repo,803we should probably avoid making ham-handed POSTS to it. Instead, let's play804with the Issues feature of GitHub.805806This documentation was added in response to807`Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that808this issue already exists, we will use it as an example. Let's start by getting it.809810::811812 >>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')813 >>> r.status_code814 200815816 >>> issue = json.loads(r.text)817818 >>> print(issue['title'])819 Feature any http verb in docs820821 >>> print(issue['comments'])822 3823824Cool, we have three comments. Let's take a look at the last of them.825826::827828 >>> r = requests.get(r.url + '/comments')829 >>> r.status_code830 200831832 >>> comments = r.json()833834 >>> print(comments[0].keys())835 ['body', 'url', 'created_at', 'updated_at', 'user', 'id']836837 >>> print(comments[2]['body'])838 Probably in the "advanced" section839840Well, that seems like a silly place. Let's post a comment telling the poster841that he's silly. Who is the poster, anyway?842843::844845 >>> print(comments[2]['user']['login'])846 kennethreitz847848OK, so let's tell this Kenneth guy that we think this example should go in the849quickstart guide instead. According to the GitHub API doc, the way to do this850is to POST to the thread. Let's do it.851852::853854 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})855 >>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"856857 >>> r = requests.post(url=url, data=body)858 >>> r.status_code859 404860861Huh, that's weird. We probably need to authenticate. That'll be a pain, right?862Wrong. Requests makes it easy to use many forms of authentication, including863the very common Basic Auth.864865::866867 >>> from requests.auth import HTTPBasicAuth868 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')869870 >>> r = requests.post(url=url, data=body, auth=auth)871 >>> r.status_code872 201873874 >>> content = r.json()875 >>> print(content['body'])876 Sounds great! I'll get right on it.877878Brilliant. Oh, wait, no! I meant to add that it would take me a while, because879I had to go feed my cat. If only I could edit this comment! Happily, GitHub880allows us to use another HTTP verb, PATCH, to edit this comment. Let's do881that.882883::884885 >>> print(content[u"id"])886 5804413887888 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})889 >>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"890891 >>> r = requests.patch(url=url, data=body, auth=auth)892 >>> r.status_code893 200894895Excellent. Now, just to torture this Kenneth guy, I've decided to let him896sweat and not tell him that I'm working on this. That means I want to delete897this comment. GitHub lets us delete comments using the incredibly aptly named898DELETE method. Let's get rid of it.899900::901902 >>> r = requests.delete(url=url, auth=auth)903 >>> r.status_code904 204905 >>> r.headers['status']906 '204 No Content'907908Excellent. All gone. The last thing I want to know is how much of my ratelimit909I've used. Let's find out. GitHub sends that information in the headers, so910rather than download the whole page I'll send a HEAD request to get the911headers.912913::914915 >>> r = requests.head(url=url, auth=auth)916 >>> print(r.headers)917 ...918 'x-ratelimit-remaining': '4995'919 'x-ratelimit-limit': '5000'920 ...921922Excellent. Time to write a Python program that abuses the GitHub API in all923kinds of exciting ways, 4995 more times.924925.. _custom-verbs:926927Custom Verbs928------------929930From time to time you may be working with a server that, for whatever reason,931allows use or even requires use of HTTP verbs not covered above. One example of932this would be the MKCOL method some WEBDAV servers use. Do not fret, these can933still be used with Requests. These make use of the built-in ``.request``934method. For example::935936 >>> r = requests.request('MKCOL', url, data=data)937 >>> r.status_code938 200 # Assuming your call was correct939940Utilising this, you can make use of any method verb that your server allows.941942943.. _link-headers:944945Link Headers946------------947948Many HTTP APIs feature Link headers. They make APIs more self describing and949discoverable.950Merge pull request #6583 from EFord36/fix-broken-linksIan Stapleton Cordascobefore adoptionf3f2611
line 951why, one step back951GitHub uses these for `pagination <https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api>`_Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 952–998why, one step back952in their API, for example::953954 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'955 >>> r = requests.head(url=url)956 >>> r.headers['link']957 '<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"'958959Requests will automatically parse these link headers and make them easily consumable::960961 >>> r.links["next"]962 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}963964 >>> r.links["last"]965 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}966967.. _transport-adapters:968969Transport Adapters970------------------971972As of v1.0.0, Requests has moved to a modular internal design. Part of the973reason this was done was to implement Transport Adapters, originally974`described here`_. Transport Adapters provide a mechanism to define interaction975methods for an HTTP service. In particular, they allow you to apply per-service976configuration.977978Requests ships with a single Transport Adapter, the :class:`HTTPAdapter979<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests980interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever981a Requests :class:`Session <requests.Session>` is initialized, one of these is982attached to the :class:`Session <requests.Session>` object for HTTP, and one983for HTTPS.984985Requests enables users to create and use their own Transport Adapters that986provide specific functionality. Once created, a Transport Adapter can be987mounted to a Session object, along with an indication of which web services988it should apply to.989990::991992 >>> s = requests.Session()993 >>> s.mount('https://github.com/', MyAdapter())994995The mount call registers a specific instance of a Transport Adapter to a996prefix. Once mounted, any HTTP request made using that session whose URL starts997with the given prefix will use the given Transport Adapter.998Add note about adapter prefix match to docs (#6465)Calle Svenssonbefore adoptionaa4cc78
lines 999–1002why, one step back999.. note:: The adapter will be chosen based on a longest prefix match. Be mindful1000 prefixes such as ``http://localhost`` will also match ``http://localhost.other.com``1001 or ``http://localhost@other.com``. It's recommended to terminate full hostnames with a ``/``.1002Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1003–1034why, one step back1003Many of the details of implementing a Transport Adapter are beyond the scope of1004this documentation, but take a look at the next example for a simple SSL use-1005case. For more than that, you might look at subclassing the1006:class:`BaseAdapter <requests.adapters.BaseAdapter>`.10071008Example: Specific SSL Version1009^^^^^^^^^^^^^^^^^^^^^^^^^^^^^10101011The Requests team has made a specific choice to use whatever SSL version is1012default in the underlying library (`urllib3`_). Normally this is fine, but from1013time to time, you might find yourself needing to connect to a service-endpoint1014that uses a version that isn't compatible with the default.10151016You can use Transport Adapters for this by taking most of the existing1017implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets1018passed-through to `urllib3`. We'll make a Transport Adapter that instructs the1019library to use SSLv3::10201021 import ssl1022 from urllib3.poolmanager import PoolManager10231024 from requests.adapters import HTTPAdapter102510261027 class Ssl3HttpAdapter(HTTPAdapter):1028 """"Transport adapter" that allows us to use SSLv3."""10291030 def init_poolmanager(self, connections, maxsize, block=False):1031 self.poolmanager = PoolManager(1032 num_pools=connections, maxsize=maxsize,1033 block=block, ssl_version=ssl.PROTOCOL_SSLv3)1034Add an Example for automatic retries to the Advanced Usage docs (#6258)Matthew Armandbefore adoptioncdbc2e2
lines 1035–1055why, one step back1035Example: Automatic Retries1036^^^^^^^^^^^^^^^^^^^^^^^^^^10371038By default, Requests does not retry failed connections. However, it is possible1039to implement automatic retries with a powerful array of features, including1040backoff, within a Requests :class:`Session <requests.Session>` using the1041`urllib3.util.Retry`_ class::10421043 from urllib3.util import Retry1044 from requests import Session1045 from requests.adapters import HTTPAdapter10461047 s = Session()1048 retries = Retry(1049 total=3,1050 backoff_factor=0.1,1051 status_forcelist=[502, 503, 504],1052 allowed_methods={'POST'},1053 )1054 s.mount('https://', HTTPAdapter(max_retries=retries))1055Fix broken link to adapters essay (#5899)Israel Tsadokbefore adoptionb0e025a
line 1056why, one step back1056.. _`described here`: https://kenreitz.org/essays/2012/06/14/the-future-of-python-httpFix GitHub links (#5835)Francois Marierbefore adoption1466ad7
line 1057why, one step back1057.. _`urllib3`: https://github.com/urllib3/urllib3Add an Example for automatic retries to the Advanced Usage docs (#6258)Matthew Armandbefore adoptioncdbc2e2
line 1058why, one step back1058.. _`urllib3.util.Retry`: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.RetryMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1059–1076why, one step back10591060.. _blocking-or-nonblocking:10611062Blocking Or Non-Blocking?1063-------------------------10641065With the default Transport Adapter in place, Requests does not provide any kind1066of non-blocking IO. The :attr:`Response.content <requests.Response.content>`1067property will block until the entire response has been downloaded. If1068you require more granularity, the streaming features of the library (see1069:ref:`streaming-requests`) allow you to retrieve smaller quantities of the1070response at a time. However, these calls will still block.10711072If you are concerned about the use of blocking IO, there are lots of projects1073out there that combine Requests with one of Python's asynchronicity frameworks.1074Some excellent examples are `requests-threads`_, `grequests`_, `requests-futures`_, and `httpx`_.10751076.. _`requests-threads`: https://github.com/requests/requests-threadsFix GitHub links (#5835)Francois Marierbefore adoption1466ad7
line 1077why, one step back1077.. _`grequests`: https://github.com/spyoungtech/grequestsMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1078–1085why, one step back1078.. _`requests-futures`: https://github.com/ross/requests-futures1079.. _`httpx`: https://github.com/encode/httpx10801081Header Ordering1082---------------10831084In unusual circumstances you may want to provide headers in an ordered manner. If you pass an ``OrderedDict`` to the ``headers`` keyword argument, that will provide the headers with an ordering. *However*, the ordering of the default headers used by Requests will be preferred, which means that if you override default headers in the ``headers`` keyword argument, they may appear out of order compared to other headers in that keyword argument.1085Specify that Session.headers needs to be set to a OrderedDict in Header Ordering docs (#6475)Joren Vranckenbefore adoptioncb7fcd7
line 1086why, one step back1086If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session.headers <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1087–1101why, one step back10871088.. _timeouts:10891090Timeouts1091--------10921093Most requests to external servers should have a timeout attached, in case the1094server is not responding in a timely manner. By default, requests do not time1095out unless a timeout value is set explicitly. Without a timeout, your code may1096hang for minutes or more.10971098The **connect** timeout is the number of seconds Requests will wait for your1099client to establish a connection to a remote machine (corresponding to the1100`connect()`_) call on the socket. It's a good practice to set connect timeouts1101to slightly larger than a multiple of 3, which is the default `TCP packetMerge pull request #6583 from EFord36/fix-broken-linksIan Stapleton Cordascobefore adoptionf3f2611
line 1102why, one step back1102retransmission window <https://datatracker.ietf.org/doc/html/rfc2988>`_.Merge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
lines 1103–1126why, one step back11031104Once your client has connected to the server and sent the HTTP request, the1105**read** timeout is the number of seconds the client will wait for the server1106to send a response. (Specifically, it's the number of seconds that the client1107will wait *between* bytes sent from the server. In 99.9% of cases, this is the1108time before the server sends the first byte).11091110If you specify a single value for the timeout, like this::11111112 r = requests.get('https://github.com', timeout=5)11131114The timeout value will be applied to both the ``connect`` and the ``read``1115timeouts. Specify a tuple if you would like to set the values separately::11161117 r = requests.get('https://github.com', timeout=(3.05, 27))11181119If the remote server is very slow, you can tell Requests to wait forever for1120a response, by passing None as a timeout value and then retrieving a cup of1121coffee.11221123::11241125 r = requests.get('https://github.com', timeout=None)1126Merge pull request #6600 from MestreLion/MestreLion-connection-timeout-noteIan Stapleton Cordascobefore adoption1ddf014
lines 1127–1140why, one step back1127.. note:: The connect timeout applies to each connection attempt to an IP address.1128 If multiple addresses exist for a domain name, the underlying ``urllib3`` will1129 try each address sequentially until one successfully connects.1130 This may lead to an effective total connection timeout *multiple* times longer1131 than the specified time, e.g. an unresponsive server having both IPv4 and IPv61132 addresses will have its perceived timeout *doubled*, so take that into account1133 when setting the connection timeout.1134.. note:: Neither the connect nor read timeouts are `wall clock`_. This means1135 that if you start a request, and look at the time, and then look at1136 the time when the request finishes or times out, the real-world time1137 may be greater than what you specified.113811391140.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_timeMerge pull request #5681 from mateusduboli/5677Ian Stapleton Cordascobefore adoption8c211a9
line 1141why, one step back1141.. _`connect()`: https://linux.die.net/man/2/connect