Skip to content
Myr

advanced.rst

This file

Path

docs/user/advanced.rst

1,032 lines · 36.1 KiB

Last changed by

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

History of this file

Take it

The walk stopped after 200 commits: lines older than 8546a15 point at it.

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 1–27why, one step back
1.. _advanced:
23Advanced Usage4==============56.. image:: https://farm5.staticflickr.com/4263/35163665790_d182d84f5e_k_d.jpg78This document covers some of Requests more advanced features.910.. _session-objects:1112Session Objects13---------------1415The Session object allows you to persist certain parameters across16requests. It also persists cookies across all requests made from the17Session instance, and will use ``urllib3``'s `connection pooling`_. So if18you're making several requests to the same host, the underlying TCP19connection will be reused, which can result in a significant performance20increase (see `HTTP persistent connection`_).2122A Session object has all the methods of the main Requests API.2324Let's persist some cookies across requests::2526 s = requests.Session()27

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

lines 28–29why, one step back
28 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
29 r = s.get('https://httpbin.org/cookies')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 30–42why, one step back
30
31 print(r.text)32 # '{"cookies": {"sessioncookie": "123456789"}}'333435Sessions can also be used to provide default data to the request methods. This36is done by providing data to the properties on a Session object::3738 s = requests.Session()39 s.auth = ('user', 'pass')40 s.headers.update({'x-test': 'true'})4142 # both 'x-test' and 'x-test2' are sent

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 43why, one step back
43 s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 44–55why, one step back
44
4546Any dictionaries that you pass to a request method will be merged with the47session-level values that are set. The method-level parameters override session48parameters.4950Note, however, that method-level parameters will *not* be persisted across51requests, even if using a session. This example will only send the cookies52with the first request, but not the second::5354 s = requests.Session()55

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 56why, one step back
56 r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 57–59why, one step back
57 print(r.text)
58 # '{"cookies": {"from-my": "browser"}}'59

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 60why, one step back
60 r = s.get('https://httpbin.org/cookies')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 61–71why, one step back
61 print(r.text)
62 # '{"cookies": {}}'636465If you want to manually add cookies to your session, use the66:ref:`Cookie utility functions <api-cookies>` to manipulate67:attr:`Session.cookies <requests.Session.cookies>`.6869Sessions can also be used as context managers::7071 with requests.Session() as s:

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 72why, one step back
72 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 73–99why, one step back
73
74This will make sure the session is closed as soon as the ``with`` block is75exited, even if unhandled exceptions occurred.767778.. admonition:: Remove a Value From a Dict Parameter7980 Sometimes you'll want to omit session-level keys from a dict parameter. To81 do this, you simply set that key's value to ``None`` in the method-level82 parameter. It will automatically be omitted.8384All values that are contained within a session are directly available to you.85See the :ref:`Session API Docs <sessionapi>` to learn more.8687.. _request-and-response-objects:8889Request and Response Objects90----------------------------9192Whenever a call is made to ``requests.get()`` and friends, you are doing two93major things. First, you are constructing a ``Request`` object which will be94sent off to a server to request or query some resource. Second, a ``Response``95object is generated once Requests gets a response back from the server.96The ``Response`` object contains all of the information returned by the server and97also contains the ``Request`` object you created originally. Here is a simple98request to get some very important information from Wikipedia's servers::99

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 100why, one step back
100 >>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 101–195why, one step back
101
102If we want to access the headers the server sent back to us, we do this::103104 >>> r.headers105 {'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':106 'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':107 'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',108 'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',109 'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,110 must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':111 'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,112 MISS from cp1010.eqiad.wmnet:80'}113114However, if we want to get the headers we sent the server, we simply access the115request, and then the request's headers::116117 >>> r.request.headers118 {'Accept-Encoding': 'identity, deflate, compress, gzip',119 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}120121.. _prepared-requests:122123Prepared Requests124-----------------125126Whenever you receive a :class:`Response <requests.Response>` object127from an API call or a Session call, the ``request`` attribute is actually the128``PreparedRequest`` that was used. In some cases you may wish to do some extra129work to the body or headers (or anything else really) before sending a130request. The simple recipe for this is the following::131132 from requests import Request, Session133134 s = Session()135136 req = Request('POST', url, data=data, headers=headers)137 prepped = req.prepare()138139 # do something with prepped.body140 prepped.body = 'No, I want exactly this as the body.'141142 # do something with prepped.headers143 del prepped.headers['Content-Type']144145 resp = s.send(prepped,146 stream=stream,147 verify=verify,148 proxies=proxies,149 cert=cert,150 timeout=timeout151 )152153 print(resp.status_code)154155Since you are not doing anything special with the ``Request`` object, you156prepare it immediately and modify the ``PreparedRequest`` object. You then157send that with the other parameters you would have sent to ``requests.*`` or158``Session.*``.159160However, the above code will lose some of the advantages of having a Requests161:class:`Session <requests.Session>` object. In particular,162:class:`Session <requests.Session>`-level state such as cookies will163not get applied to your request. To get a164:class:`PreparedRequest <requests.PreparedRequest>` with that state165applied, replace the call to :meth:`Request.prepare()166<requests.Request.prepare>` with a call to167:meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::168169 from requests import Request, Session170171 s = Session()172 req = Request('GET', url, data=data, headers=headers)173174 prepped = s.prepare_request(req)175176 # do something with prepped.body177 prepped.body = 'Seriously, send exactly these bytes.'178179 # do something with prepped.headers180 prepped.headers['Keep-Dead'] = 'parrot'181182 resp = s.send(prepped,183 stream=stream,184 verify=verify,185 proxies=proxies,186 cert=cert,187 timeout=timeout188 )189190 print(resp.status_code)191192When you are using the prepared request flow, keep in mind that it does not take into account the environment.193This can cause problems if you are using environment variables to change the behaviour of requests.194For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.195As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.

Merge pull request #5141 from minho42/Fix-typosKenneth Reitzbefore adoption589a822

line 196why, one step back
196You can get around this behaviour by explicitly merging the environment settings into your session::

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 197–205why, one step back
197
198 from requests import Request, Session199200 s = Session()201 req = Request('GET', url)202203 prepped = s.prepare_request(req)204205 # Merge environment settings into session

Merge pull request #4960 from andrewbonney/masterIan Stapleton Cordascobefore adoptionc9309e4

line 206why, one step back
206 settings = s.merge_environment_settings(prepped.url, {}, None, None, None)

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 207–302why, one step back
207 resp = s.send(prepped, **settings)
208209 print(resp.status_code)210211.. _verification:212213SSL Cert Verification214---------------------215216Requests verifies SSL certificates for HTTPS requests, just like a web browser.217By default, SSL verification is enabled, and Requests will throw a SSLError if218it's unable to verify the certificate::219220 >>> requests.get('https://requestb.in')221 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'222223I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::224225 >>> requests.get('https://github.com')226 <Response [200]>227228You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::229230 >>> requests.get('https://github.com', verify='/path/to/certfile')231232or persistent::233234 s = requests.Session()235 s.verify = '/path/to/certfile'236237.. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using238 the c_rehash utility supplied with OpenSSL.239240This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.241242Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::243244 >>> requests.get('https://kennethreitz.org', verify=False)245 <Response [200]>246247By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.248249Client Side Certificates250------------------------251252You can also specify a local cert to use as client side certificate, as a single253file (containing the private key and the certificate) or as a tuple of both254files' paths::255256 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))257 <Response [200]>258259or persistent::260261 s = requests.Session()262 s.cert = '/path/client.cert'263264If you specify a wrong path or an invalid cert, you'll get a SSLError::265266 >>> requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')267 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib268269.. warning:: The private key to your local certificate *must* be unencrypted.270 Currently, Requests does not support using encrypted keys.271272.. _ca-certificates:273274CA Certificates275---------------276277Requests uses certificates from the package `certifi`_. This allows for users278to update their trusted certificates without changing the version of Requests.279280Before version 2.16, Requests bundled a set of root CAs that it trusted,281sourced from the `Mozilla trust store`_. The certificates were only updated282once for each Requests version. When ``certifi`` was not installed, this led to283extremely out-of-date certificate bundles when using significantly older284versions of Requests.285286For the sake of security we recommend upgrading certifi frequently!287288.. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection289.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool290.. _certifi: https://certifiio.readthedocs.io/291.. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt292293.. _body-content-workflow:294295Body Content Workflow296---------------------297298By default, when you make a request, the body of the response is downloaded299immediately. You can override this behaviour and defer downloading the response300body until you access the :attr:`Response.content <requests.Response.content>`301attribute with the ``stream`` parameter::302

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 303why, one step back
303 tarball_url = 'https://github.com/psf/requests/tarball/master'

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 304–325why, one step back
304 r = requests.get(tarball_url, stream=True)
305306At this point only the response headers have been downloaded and the connection307remains open, hence allowing us to make content retrieval conditional::308309 if int(r.headers['content-length']) < TOO_LONG:310 content = r.content311 ...312313You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`314and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.315Alternatively, you can read the undecoded body from the underlying316urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at317:attr:`Response.raw <requests.Response.raw>`.318319If you set ``stream`` to ``True`` when making a request, Requests cannot320release the connection back to the pool unless you consume all the data or call321:meth:`Response.close <requests.Response.close>`. This can lead to322inefficiency with connections. If you find yourself partially reading request323bodies (or not reading them at all) while using ``stream=True``, you should324make the request within a ``with`` statement to ensure it's always closed::325

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 326why, one step back
326 with requests.get('https://httpbin.org/get', stream=True) as r:

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 327–353why, one step back
327 # Do things with the response here.
328329.. _keep-alive:330331Keep-Alive332----------333334Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!335Any requests that you make within a session will automatically reuse the appropriate336connection!337338Note that connections are only released back to the pool for reuse once all body339data has been read; be sure to either set ``stream`` to ``False`` or read the340``content`` property of the ``Response`` object.341342.. _streaming-uploads:343344Streaming Uploads345-----------------346347Requests supports streaming uploads, which allow you to send large streams or348files without reading them into memory. To stream and upload, simply provide a349file-like object for your body::350351 with open('massive-body', 'rb') as f:352 requests.post('http://some.url/streamed', data=f)353

Merge pull request #4678 from jdufresne/intersphinxNate Prewittbefore adoptiondffd5d4

lines 354–358why, one step back
354.. warning:: It is strongly recommended that you open files in :ref:`binary
355 mode <tut-files>`. This is because Requests may attempt to provide356 the ``Content-Length`` header for you, and if it does this value357 will be set to the number of *bytes* in the file. Errors may occur358 if you open the file in *text mode*.

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 359–395why, one step back
359
360361.. _chunk-encoding:362363Chunk-Encoded Requests364----------------------365366Requests also supports Chunked transfer encoding for outgoing and incoming requests.367To send a chunk-encoded request, simply provide a generator (or any iterator without368a length) for your body::369370 def gen():371 yield 'hi'372 yield 'there'373374 requests.post('http://some.url/chunked', data=gen())375376For chunked encoded responses, it's best to iterate over the data using377:meth:`Response.iter_content() <requests.Response.iter_content>`. In378an ideal situation you'll have set ``stream=True`` on the request, in which379case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``380parameter of ``None``. If you want to set a maximum size of the chunk,381you can set a ``chunk_size`` parameter to any integer.382383384.. _multipart:385386POST Multiple Multipart-Encoded Files387-------------------------------------388389You can send multiple files in one request. For example, suppose you want to390upload image files to an HTML form with a multiple file field 'images'::391392 <input type="file" name="images" multiple="true" required="true"/>393394To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::395

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 396why, one step back
396 >>> url = 'https://httpbin.org/post'

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 397–408why, one step back
397 >>> multiple_files = [
398 ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),399 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]400 >>> r = requests.post(url, files=multiple_files)401 >>> r.text402 {403 ...404 'files': {'images': 'data:image/png;base64,iVBORw ....'}405 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',406 ...407 }408

Merge pull request #4678 from jdufresne/intersphinxNate Prewittbefore adoptiondffd5d4

lines 409–413why, one step back
409.. warning:: It is strongly recommended that you open files in :ref:`binary
410 mode <tut-files>`. This is because Requests may attempt to provide411 the ``Content-Length`` header for you, and if it does this value412 will be set to the number of *bytes* in the file. Errors may occur413 if you open the file in *text mode*.

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 414–457why, one step back
414
415416.. _event-hooks:417418Event Hooks419-----------420421Requests has a hook system that you can use to manipulate portions of422the request process, or signal event handling.423424Available hooks:425426``response``:427 The response generated from a Request.428429430You can assign a hook function on a per-request basis by passing a431``{hook_name: callback_function}`` dictionary to the ``hooks`` request432parameter::433434 hooks={'response': print_url}435436That ``callback_function`` will receive a chunk of data as its first437argument.438439::440441 def print_url(r, *args, **kwargs):442 print(r.url)443444If an error occurs while executing your callback, a warning is given.445446If the callback function returns a value, it is assumed that it is to447replace the data that was passed in. If the function doesn't return448anything, nothing else is affected.449450::451452 def record_hook(r, *args, **kwargs):453 r.hook_called = True454 return r455456Let's print some request method arguments at runtime::457

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

lines 458–459why, one step back
458 >>> requests.get('https://httpbin.org/', hooks={'response': print_url})
459 https://httpbin.org/

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 460–463why, one step back
460 <Response [200]>
461462You can add multiple hooks to a single request. Let's call two hooks at once::463

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 464why, one step back
464 >>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 465–472why, one step back
465 >>> r.hook_called
466 True467468You can also add hooks to a ``Session`` instance. Any hooks you add will then469be called on every request made to the session. For example::470471 >>> s = requests.Session()472 >>> s.hooks['response'].append(print_url)

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

lines 473–474why, one step back
473 >>> s.get('https://httpbin.org/')
474 https://httpbin.org/

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 475–531why, one step back
475 <Response [200]>
476477A ``Session`` can have multiple hooks, which will be called in the order478they are added.479480.. _custom-auth:481482Custom Authentication483---------------------484485Requests allows you to use specify your own authentication mechanism.486487Any callable which is passed as the ``auth`` argument to a request method will488have the opportunity to modify the request before it is dispatched.489490Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,491and are easy to define. Requests provides two common authentication scheme492implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and493:class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.494495Let's pretend that we have a web service that will only respond if the496``X-Pizza`` header is set to a password value. Unlikely, but just go with it.497498::499500 from requests.auth import AuthBase501502 class PizzaAuth(AuthBase):503 """Attaches HTTP Pizza Authentication to the given Request object."""504 def __init__(self, username):505 # setup any auth-related data here506 self.username = username507508 def __call__(self, r):509 # modify and return the request510 r.headers['X-Pizza'] = self.username511 return r512513Then, we can make a request using our Pizza Auth::514515 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))516 <Response [200]>517518.. _streaming-requests:519520Streaming Requests521------------------522523With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily524iterate over streaming APIs such as the `Twitter Streaming525API <https://dev.twitter.com/streaming/overview>`_. Simply526set ``stream`` to ``True`` and iterate over the response with527:meth:`~requests.Response.iter_lines()`::528529 import json530 import requests531

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 532why, one step back
532 r = requests.get('https://httpbin.org/stream/20', stream=True)

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 533–545why, one step back
533
534 for line in r.iter_lines():535536 # filter out keep-alive new lines537 if line:538 decoded_line = line.decode('utf-8')539 print(json.loads(decoded_line))540541When using `decode_unicode=True` with542:meth:`Response.iter_lines() <requests.Response.iter_lines>` or543:meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want544to provide a fallback encoding in the event the server doesn't provide one::545

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 546why, one step back
546 r = requests.get('https://httpbin.org/stream/20', stream=True)

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 547–659why, one step back
547
548 if r.encoding is None:549 r.encoding = 'utf-8'550551 for line in r.iter_lines(decode_unicode=True):552 if line:553 print(json.loads(line))554555.. warning::556557 :meth:`~requests.Response.iter_lines()` is not reentrant safe.558 Calling this method multiple times causes some of the received data559 being lost. In case you need to call it from multiple places, use560 the resulting iterator object instead::561562 lines = r.iter_lines()563 # Save the first line for later or just skip it564565 first_line = next(lines)566567 for line in lines:568 print(line)569570.. _proxies:571572Proxies573-------574575If you need to use a proxy, you can configure individual requests with the576``proxies`` argument to any request method::577578 import requests579580 proxies = {581 'http': 'http://10.10.1.10:3128',582 'https': 'http://10.10.1.10:1080',583 }584585 requests.get('http://example.org', proxies=proxies)586587You can also configure proxies by setting the environment variables588``HTTP_PROXY`` and ``HTTPS_PROXY``.589590::591592 $ export HTTP_PROXY="http://10.10.1.10:3128"593 $ export HTTPS_PROXY="http://10.10.1.10:1080"594595 $ python596 >>> import requests597 >>> requests.get('http://example.org')598599To use HTTP Basic Auth with your proxy, use the `http://user:password@host/` syntax::600601 proxies = {'http': 'http://user:pass@10.10.1.10:3128/'}602603To give a proxy for a specific scheme and host, use the604`scheme://hostname` form for the key. This will match for605any request to the given scheme and exact hostname.606607::608609 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}610611Note that proxy URLs must include the scheme.612613SOCKS614^^^^^615616.. versionadded:: 2.10.0617618In addition to basic HTTP proxies, Requests also supports proxies using the619SOCKS protocol. This is an optional feature that requires that additional620third-party libraries be installed before use.621622You can get the dependencies for this feature from ``pip``:623624.. code-block:: bash625626 $ pip install requests[socks]627628Once you've installed those dependencies, using a SOCKS proxy is just as easy629as using a HTTP one::630631 proxies = {632 'http': 'socks5://user:pass@host:port',633 'https': 'socks5://user:pass@host:port'634 }635636Using 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.637638.. _compliance:639640Compliance641----------642643Requests is intended to be compliant with all relevant specifications and644RFCs where that compliance will not cause difficulties for users. This645attention to the specification can lead to some behaviour that may seem646unusual to those not familiar with the relevant specification.647648Encodings649^^^^^^^^^650651When you receive a response, Requests makes a guess at the encoding to652use for decoding the response when you access the :attr:`Response.text653<requests.Response.text>` attribute. Requests will first check for an654encoding in the HTTP header, and if none is present, will use `chardet655<https://pypi.org/project/chardet/>`_ to attempt to guess the encoding.656657The only time Requests will not do this is if no explicit charset658is present in the HTTP headers **and** the ``Content-Type``659header contains ``text``. In this situation, `RFC 2616

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 660why, one step back
660<https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 661–682why, one step back
661that the default charset must be ``ISO-8859-1``. Requests follows the
662specification in this case. If you require a different encoding, you can663manually set the :attr:`Response.encoding <requests.Response.encoding>`664property, or use the raw :attr:`Response.content <requests.Response.content>`.665666.. _http-verbs:667668HTTP Verbs669----------670671Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,672HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of673using these various verbs in Requests, using the GitHub API.674675We will begin with the verb most commonly used: GET. HTTP GET is an idempotent676method that returns a resource from a given URL. As a result, it is the verb677you ought to use when attempting to retrieve data from a web location. An678example usage would be attempting to get information about a specific commit679from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it680like so::681682 >>> import requests

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 683why, one step back
683 >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 684–737why, one step back
684
685We should confirm that GitHub responded correctly. If it has, we want to work686out what type of content it is. Do this like so::687688 >>> if r.status_code == requests.codes.ok:689 ... print(r.headers['content-type'])690 ...691 application/json; charset=utf-8692693So, GitHub returns JSON. That's great, we can use the :meth:`r.json694<requests.Response.json>` method to parse it into Python objects.695696::697698 >>> commit_data = r.json()699700 >>> print(commit_data.keys())701 [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']702703 >>> print(commit_data[u'committer'])704 {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}705706 >>> print(commit_data[u'message'])707 makin' history708709So far, so simple. Well, let's investigate the GitHub API a little bit. Now,710we could look at the documentation, but we might have a little more fun if we711use Requests instead. We can take advantage of the Requests OPTIONS verb to712see what kinds of HTTP methods are supported on the url we just used.713714::715716 >>> verbs = requests.options(r.url)717 >>> verbs.status_code718 500719720Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't721actually implement the OPTIONS method. This is an annoying oversight, but it's722OK, we can just use the boring documentation. If GitHub had correctly723implemented OPTIONS, however, they should return the allowed methods in the724headers, e.g.725726::727728 >>> verbs = requests.options('http://a-good-website.com/api/cats')729 >>> print(verbs.headers['allow'])730 GET,HEAD,POST,OPTIONS731732Turning to the documentation, we see that the only other method allowed for733commits is POST, which creates a new commit. As we're using the Requests repo,734we should probably avoid making ham-handed POSTS to it. Instead, let's play735with the Issues feature of GitHub.736737This documentation was added in response to

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 738why, one step back
738`Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 739–742why, one step back
739this issue already exists, we will use it as an example. Let's start by getting it.
740741::742

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 743why, one step back
743 >>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 744–785why, one step back
744 >>> r.status_code
745 200746747 >>> issue = json.loads(r.text)748749 >>> print(issue[u'title'])750 Feature any http verb in docs751752 >>> print(issue[u'comments'])753 3754755Cool, we have three comments. Let's take a look at the last of them.756757::758759 >>> r = requests.get(r.url + u'/comments')760 >>> r.status_code761 200762763 >>> comments = r.json()764765 >>> print(comments[0].keys())766 [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']767768 >>> print(comments[2][u'body'])769 Probably in the "advanced" section770771Well, that seems like a silly place. Let's post a comment telling the poster772that he's silly. Who is the poster, anyway?773774::775776 >>> print(comments[2][u'user'][u'login'])777 kennethreitz778779OK, so let's tell this Kenneth guy that we think this example should go in the780quickstart guide instead. According to the GitHub API doc, the way to do this781is to POST to the thread. Let's do it.782783::784785 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 786why, one step back
786 >>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 787–819why, one step back
787
788 >>> r = requests.post(url=url, data=body)789 >>> r.status_code790 404791792Huh, that's weird. We probably need to authenticate. That'll be a pain, right?793Wrong. Requests makes it easy to use many forms of authentication, including794the very common Basic Auth.795796::797798 >>> from requests.auth import HTTPBasicAuth799 >>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')800801 >>> r = requests.post(url=url, data=body, auth=auth)802 >>> r.status_code803 201804805 >>> content = r.json()806 >>> print(content[u'body'])807 Sounds great! I'll get right on it.808809Brilliant. Oh, wait, no! I meant to add that it would take me a while, because810I had to go feed my cat. If only I could edit this comment! Happily, GitHub811allows us to use another HTTP verb, PATCH, to edit this comment. Let's do812that.813814::815816 >>> print(content[u"id"])817 5804413818819 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 820why, one step back
820 >>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 821–923why, one step back
821
822 >>> r = requests.patch(url=url, data=body, auth=auth)823 >>> r.status_code824 200825826Excellent. Now, just to torture this Kenneth guy, I've decided to let him827sweat and not tell him that I'm working on this. That means I want to delete828this comment. GitHub lets us delete comments using the incredibly aptly named829DELETE method. Let's get rid of it.830831::832833 >>> r = requests.delete(url=url, auth=auth)834 >>> r.status_code835 204836 >>> r.headers['status']837 '204 No Content'838839Excellent. All gone. The last thing I want to know is how much of my ratelimit840I've used. Let's find out. GitHub sends that information in the headers, so841rather than download the whole page I'll send a HEAD request to get the842headers.843844::845846 >>> r = requests.head(url=url, auth=auth)847 >>> print(r.headers)848 ...849 'x-ratelimit-remaining': '4995'850 'x-ratelimit-limit': '5000'851 ...852853Excellent. Time to write a Python program that abuses the GitHub API in all854kinds of exciting ways, 4995 more times.855856.. _custom-verbs:857858Custom Verbs859------------860861From time to time you may be working with a server that, for whatever reason,862allows use or even requires use of HTTP verbs not covered above. One example of863this would be the MKCOL method some WEBDAV servers use. Do not fret, these can864still be used with Requests. These make use of the built-in ``.request``865method. For example::866867 >>> r = requests.request('MKCOL', url, data=data)868 >>> r.status_code869 200 # Assuming your call was correct870871Utilising this, you can make use of any method verb that your server allows.872873874.. _link-headers:875876Link Headers877------------878879Many HTTP APIs feature Link headers. They make APIs more self describing and880discoverable.881882GitHub uses these for `pagination <https://developer.github.com/v3/#pagination>`_883in their API, for example::884885 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'886 >>> r = requests.head(url=url)887 >>> r.headers['link']888 '<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"'889890Requests will automatically parse these link headers and make them easily consumable::891892 >>> r.links["next"]893 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}894895 >>> r.links["last"]896 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}897898.. _transport-adapters:899900Transport Adapters901------------------902903As of v1.0.0, Requests has moved to a modular internal design. Part of the904reason this was done was to implement Transport Adapters, originally905`described here`_. Transport Adapters provide a mechanism to define interaction906methods for an HTTP service. In particular, they allow you to apply per-service907configuration.908909Requests ships with a single Transport Adapter, the :class:`HTTPAdapter910<requests.adapters.HTTPAdapter>`. This adapter provides the default Requests911interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever912a Requests :class:`Session <requests.Session>` is initialized, one of these is913attached to the :class:`Session <requests.Session>` object for HTTP, and one914for HTTPS.915916Requests enables users to create and use their own Transport Adapters that917provide specific functionality. Once created, a Transport Adapter can be918mounted to a Session object, along with an indication of which web services919it should apply to.920921::922923 >>> s = requests.Session()

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 924why, one step back
924 >>> s.mount('https://github.com/', MyAdapter())

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 925–961why, one step back
925
926The mount call registers a specific instance of a Transport Adapter to a927prefix. Once mounted, any HTTP request made using that session whose URL starts928with the given prefix will use the given Transport Adapter.929930Many of the details of implementing a Transport Adapter are beyond the scope of931this documentation, but take a look at the next example for a simple SSL use-932case. For more than that, you might look at subclassing the933:class:`BaseAdapter <requests.adapters.BaseAdapter>`.934935Example: Specific SSL Version936^^^^^^^^^^^^^^^^^^^^^^^^^^^^^937938The Requests team has made a specific choice to use whatever SSL version is939default in the underlying library (`urllib3`_). Normally this is fine, but from940time to time, you might find yourself needing to connect to a service-endpoint941that uses a version that isn't compatible with the default.942943You can use Transport Adapters for this by taking most of the existing944implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets945passed-through to `urllib3`. We'll make a Transport Adapter that instructs the946library to use SSLv3::947948 import ssl949 from urllib3.poolmanager import PoolManager950951 from requests.adapters import HTTPAdapter952953954 class Ssl3HttpAdapter(HTTPAdapter):955 """"Transport adapter" that allows us to use SSLv3."""956957 def init_poolmanager(self, connections, maxsize, block=False):958 self.poolmanager = PoolManager(959 num_pools=connections, maxsize=maxsize,960 block=block, ssl_version=ssl.PROTOCOL_SSLv3)961

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 962why, one step back
962.. _`described here`: https://www.kennethreitz.org/essays/the-future-of-python-http

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 963–978why, one step back
963.. _`urllib3`: https://github.com/shazow/urllib3
964965.. _blocking-or-nonblocking:966967Blocking Or Non-Blocking?968-------------------------969970With the default Transport Adapter in place, Requests does not provide any kind971of non-blocking IO. The :attr:`Response.content <requests.Response.content>`972property will block until the entire response has been downloaded. If973you require more granularity, the streaming features of the library (see974:ref:`streaming-requests`) allow you to retrieve smaller quantities of the975response at a time. However, these calls will still block.976977If you are concerned about the use of blocking IO, there are lots of projects978out there that combine Requests with one of Python's asynchronicity frameworks.

Merge pull request #5034 from tomchristie/patch-1Kenneth Reitzbefore adoptione73a6c5

line 979why, one step back
979Some excellent examples are `requests-threads`_, `grequests`_, `requests-futures`_, and `requests-async`_.

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 980–983why, one step back
980
981.. _`requests-threads`: https://github.com/requests/requests-threads982.. _`grequests`: https://github.com/kennethreitz/grequests983.. _`requests-futures`: https://github.com/ross/requests-futures

Merge pull request #5034 from tomchristie/patch-1Kenneth Reitzbefore adoptione73a6c5

line 984why, one step back
984.. _`requests-async`: https://github.com/encode/requests-async

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 985–1006why, one step back
985
986Header Ordering987---------------988989In 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.990991If this is problematic, users should consider setting the default headers on a :class:`Session <requests.Session>` object, by setting :attr:`Session <requests.Session.headers>` to a custom ``OrderedDict``. That ordering will always be preferred.992993.. _timeouts:994995Timeouts996--------997998Most requests to external servers should have a timeout attached, in case the999server is not responding in a timely manner. By default, requests do not time1000out unless a timeout value is set explicitly. Without a timeout, your code may1001hang for minutes or more.10021003The **connect** timeout is the number of seconds Requests will wait for your1004client to establish a connection to a remote machine (corresponding to the1005`connect()`_) call on the socket. It's a good practice to set connect timeouts1006to slightly larger than a multiple of 3, which is the default `TCP packet

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 1007why, one step back
1007retransmission window <https://www.hjp.at/doc/rfc/rfc2988.txt>`_.

The library raises NoneType error when file-pointer (fp) resolves to None.Rajiv Mayanibefore adoption8546a15

lines 1008–1031why, one step back
1008
1009Once your client has connected to the server and sent the HTTP request, the1010**read** timeout is the number of seconds the client will wait for the server1011to send a response. (Specifically, it's the number of seconds that the client1012will wait *between* bytes sent from the server. In 99.9% of cases, this is the1013time before the server sends the first byte).10141015If you specify a single value for the timeout, like this::10161017 r = requests.get('https://github.com', timeout=5)10181019The timeout value will be applied to both the ``connect`` and the ``read``1020timeouts. Specify a tuple if you would like to set the values separately::10211022 r = requests.get('https://github.com', timeout=(3.05, 27))10231024If the remote server is very slow, you can tell Requests to wait forever for1025a response, by passing None as a timeout value and then retrieving a cup of1026coffee.10271028::10291030 r = requests.get('https://github.com', timeout=None)1031

Merge pull request #4805 from jdufresne/httpsNate Prewittbefore adoptionff0c325

line 1032why, one step back
1032.. _`connect()`: https://linux.die.net/man/2/connect