Debian Codegraph @

docs/user/advanced.rst

raw
1 .. _advanced:
2
3 Advanced Usage
4 ==============
5
6 This document covers some of Requests more advanced features.
7
8 .. _session-objects:
9
10 Session Objects
11 ---------------
12
13 The Session object allows you to persist certain parameters across
14 requests. It also persists cookies across all requests made from the
15 Session instance, and will use ``urllib3``'s `connection pooling`_. So if
16 you're making several requests to the same host, the underlying TCP
17 connection will be reused, which can result in a significant performance
18 increase (see `HTTP persistent connection`_).
19
20 A Session object has all the methods of the main Requests API.
21
22 Let's persist some cookies across requests::
23
24 s = requests.Session()
25
26 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
27 r = s.get('https://httpbin.org/cookies')
28
29 print(r.text)
30 # '{"cookies": {"sessioncookie": "123456789"}}'
31
32
33 Sessions can also be used to provide default data to the request methods. This
34 is done by providing data to the properties on a Session object::
35
36 s = requests.Session()
37 s.auth = ('user', 'pass')
38 s.headers.update({'x-test': 'true'})
39
40 # both 'x-test' and 'x-test2' are sent
41 s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})
42
43
44 Any dictionaries that you pass to a request method will be merged with the
45 session-level values that are set. The method-level parameters override session
46 parameters.
47
48 Note, however, that method-level parameters will *not* be persisted across
49 requests, even if using a session. This example will only send the cookies
50 with the first request, but not the second::
51
52 s = requests.Session()
53
54 r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
55 print(r.text)
56 # '{"cookies": {"from-my": "browser"}}'
57
58 r = s.get('https://httpbin.org/cookies')
59 print(r.text)
60 # '{"cookies": {}}'
61
62
63 If you want to manually add cookies to your session, use the
64 :ref:`Cookie utility functions <api-cookies>` to manipulate
65 :attr:`Session.cookies <requests.Session.cookies>`.
66
67 Sessions can also be used as context managers::
68
69 with requests.Session() as s:
70 s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
71
72 This will make sure the session is closed as soon as the ``with`` block is
73 exited, even if unhandled exceptions occurred.
74
75
76 .. admonition:: Remove a Value From a Dict Parameter
77
78 Sometimes you'll want to omit session-level keys from a dict parameter. To
79 do this, you simply set that key's value to ``None`` in the method-level
80 parameter. It will automatically be omitted.
81
82 All values that are contained within a session are directly available to you.
83 See the :ref:`Session API Docs <sessionapi>` to learn more.
84
85 .. _request-and-response-objects:
86
87 Request and Response Objects
88 ----------------------------
89
90 Whenever a call is made to ``requests.get()`` and friends, you are doing two
91 major things. First, you are constructing a ``Request`` object which will be
92 sent off to a server to request or query some resource. Second, a ``Response``
93 object is generated once Requests gets a response back from the server.
94 The ``Response`` object contains all of the information returned by the server and
95 also contains the ``Request`` object you created originally. Here is a simple
96 request to get some very important information from Wikipedia's servers::
97
98 >>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')
99
100 If we want to access the headers the server sent back to us, we do this::
101
102 >>> r.headers
103 {'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'}
111
112 However, if we want to get the headers we sent the server, we simply access the
113 request, and then the request's headers::
114
115 >>> r.request.headers
116 {'Accept-Encoding': 'identity, deflate, compress, gzip',
117 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}
118
119 .. _prepared-requests:
120
121 Prepared Requests
122 -----------------
123
124 Whenever you receive a :class:`Response <requests.Response>` object
125 from an API call or a Session call, the ``request`` attribute is actually the
126 ``PreparedRequest`` that was used. In some cases you may wish to do some extra
127 work to the body or headers (or anything else really) before sending a
128 request. The simple recipe for this is the following::
129
130 from requests import Request, Session
131
132 s = Session()
133
134 req = Request('POST', url, data=data, headers=headers)
135 prepped = req.prepare()
136
137 # do something with prepped.body
138 prepped.body = 'No, I want exactly this as the body.'
139
140 # do something with prepped.headers
141 del prepped.headers['Content-Type']
142
143 resp = s.send(prepped,
144 stream=stream,
145 verify=verify,
146 proxies=proxies,
147 cert=cert,
148 timeout=timeout
149 )
150
151 print(resp.status_code)
152
153 Since you are not doing anything special with the ``Request`` object, you
154 prepare it immediately and modify the ``PreparedRequest`` object. You then
155 send that with the other parameters you would have sent to ``requests.*`` or
156 ``Session.*``.
157
158 However, the above code will lose some of the advantages of having a Requests
159 :class:`Session <requests.Session>` object. In particular,
160 :class:`Session <requests.Session>`-level state such as cookies will
161 not get applied to your request. To get a
162 :class:`PreparedRequest <requests.PreparedRequest>` with that state
163 applied, replace the call to :meth:`Request.prepare()
164 <requests.Request.prepare>` with a call to
165 :meth:`Session.prepare_request() <requests.Session.prepare_request>`, like this::
166
167 from requests import Request, Session
168
169 s = Session()
170 req = Request('GET', url, data=data, headers=headers)
171
172 prepped = s.prepare_request(req)
173
174 # do something with prepped.body
175 prepped.body = 'Seriously, send exactly these bytes.'
176
177 # do something with prepped.headers
178 prepped.headers['Keep-Dead'] = 'parrot'
179
180 resp = s.send(prepped,
181 stream=stream,
182 verify=verify,
183 proxies=proxies,
184 cert=cert,
185 timeout=timeout
186 )
187
188 print(resp.status_code)
189
190 When you are using the prepared request flow, keep in mind that it does not take into account the environment.
191 This can cause problems if you are using environment variables to change the behaviour of requests.
192 For example: Self-signed SSL certificates specified in ``REQUESTS_CA_BUNDLE`` will not be taken into account.
193 As a result an ``SSL: CERTIFICATE_VERIFY_FAILED`` is thrown.
194 You can get around this behaviour by explicitly merging the environment settings into your session::
195
196 from requests import Request, Session
197
198 s = Session()
199 req = Request('GET', url)
200
201 prepped = s.prepare_request(req)
202
203 # Merge environment settings into session
204 settings = s.merge_environment_settings(prepped.url, {}, None, None, None)
205 resp = s.send(prepped, **settings)
206
207 print(resp.status_code)
208
209 .. _verification:
210
211 SSL Cert Verification
212 ---------------------
213
214 Requests verifies SSL certificates for HTTPS requests, just like a web browser.
215 By default, SSL verification is enabled, and Requests will throw a SSLError if
216 it's unable to verify the certificate::
217
218 >>> requests.get('https://requestb.in')
219 requests.exceptions.SSLError: hostname 'requestb.in' doesn't match either of '*.herokuapp.com', 'herokuapp.com'
220
221 I don't have SSL setup on this domain, so it throws an exception. Excellent. GitHub does though::
222
223 >>> requests.get('https://github.com')
224 <Response [200]>
225
226 You can pass ``verify`` the path to a CA_BUNDLE file or directory with certificates of trusted CAs::
227
228 >>> requests.get('https://github.com', verify='/path/to/certfile')
229
230 or persistent::
231
232 s = requests.Session()
233 s.verify = '/path/to/certfile'
234
235 .. note:: If ``verify`` is set to a path to a directory, the directory must have been processed using
236 the ``c_rehash`` utility supplied with OpenSSL.
237
238 This list of trusted CAs can also be specified through the ``REQUESTS_CA_BUNDLE`` environment variable.
239 If ``REQUESTS_CA_BUNDLE`` is not set, ``CURL_CA_BUNDLE`` will be used as fallback.
240
241 Requests can also ignore verifying the SSL certificate if you set ``verify`` to False::
242
243 >>> requests.get('https://kennethreitz.org', verify=False)
244 <Response [200]>
245
246 Note that when ``verify`` is set to ``False``, requests will accept any TLS
247 certificate presented by the server, and will ignore hostname mismatches
248 and/or expired certificates, which will make your application vulnerable to
249 man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful
250 during local development or testing.
251
252 By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.
253
254 Client Side Certificates
255 ------------------------
256
257 You can also specify a local cert to use as client side certificate, as a single
258 file (containing the private key and the certificate) or as a tuple of both
259 files' paths::
260
261 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))
262 <Response [200]>
263
264 or persistent::
265
266 s = requests.Session()
267 s.cert = '/path/client.cert'
268
269 If you specify a wrong path or an invalid cert, you'll get a SSLError::
270
271 >>> 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 lib
273
274 .. warning:: The private key to your local certificate *must* be unencrypted.
275 Currently, Requests does not support using encrypted keys.
276
277 .. _ca-certificates:
278
279 CA Certificates
280 ---------------
281
282 Requests uses certificates from the package `certifi`_. This allows for users
283 to update their trusted certificates without changing the version of Requests.
284
285 Before version 2.16, Requests bundled a set of root CAs that it trusted,
286 sourced from the `Mozilla trust store`_. The certificates were only updated
287 once for each Requests version. When ``certifi`` was not installed, this led to
288 extremely out-of-date certificate bundles when using significantly older
289 versions of Requests.
290
291 For the sake of security we recommend upgrading certifi frequently!
292
293 .. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection
294 .. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.html
295 .. _certifi: https://certifiio.readthedocs.io/
296 .. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt
297
298 .. _body-content-workflow:
299
300 Body Content Workflow
301 ---------------------
302
303 By default, when you make a request, the body of the response is downloaded
304 immediately. You can override this behaviour and defer downloading the response
305 body until you access the :attr:`Response.content <requests.Response.content>`
306 attribute with the ``stream`` parameter::
307
308 tarball_url = 'https://github.com/psf/requests/tarball/main'
309 r = requests.get(tarball_url, stream=True)
310
311 At this point only the response headers have been downloaded and the connection
312 remains open, hence allowing us to make content retrieval conditional::
313
314 if int(r.headers['content-length']) < TOO_LONG:
315 content = r.content
316 ...
317
318 You can further control the workflow by use of the :meth:`Response.iter_content() <requests.Response.iter_content>`
319 and :meth:`Response.iter_lines() <requests.Response.iter_lines>` methods.
320 Alternatively, you can read the undecoded body from the underlying
321 urllib3 :class:`urllib3.HTTPResponse <urllib3.response.HTTPResponse>` at
322 :attr:`Response.raw <requests.Response.raw>`.
323
324 If you set ``stream`` to ``True`` when making a request, Requests cannot
325 release the connection back to the pool unless you consume all the data or call
326 :meth:`Response.close <requests.Response.close>`. This can lead to
327 inefficiency with connections. If you find yourself partially reading request
328 bodies (or not reading them at all) while using ``stream=True``, you should
329 make the request within a ``with`` statement to ensure it's always closed::
330
331 with requests.get('https://httpbin.org/get', stream=True) as r:
332 # Do things with the response here.
333
334 .. _keep-alive:
335
336 Keep-Alive
337 ----------
338
339 Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session!
340 Any requests that you make within a session will automatically reuse the appropriate
341 connection!
342
343 Note that connections are only released back to the pool for reuse once all body
344 data has been read; be sure to either set ``stream`` to ``False`` or read the
345 ``content`` property of the ``Response`` object.
346
347 .. _streaming-uploads:
348
349 Streaming Uploads
350 -----------------
351
352 Requests supports streaming uploads, which allow you to send large streams or
353 files without reading them into memory. To stream and upload, simply provide a
354 file-like object for your body::
355
356 with open('massive-body', 'rb') as f:
357 requests.post('http://some.url/streamed', data=f)
358
359 .. warning:: It is strongly recommended that you open files in :ref:`binary
360 mode <tut-files>`. This is because Requests may attempt to provide
361 the ``Content-Length`` header for you, and if it does this value
362 will be set to the number of *bytes* in the file. Errors may occur
363 if you open the file in *text mode*.
364
365
366 .. _chunk-encoding:
367
368 Chunk-Encoded Requests
369 ----------------------
370
371 Requests also supports Chunked transfer encoding for outgoing and incoming requests.
372 To send a chunk-encoded request, simply provide a generator (or any iterator without
373 a length) for your body::
374
375 def gen():
376 yield 'hi'
377 yield 'there'
378
379 requests.post('http://some.url/chunked', data=gen())
380
381 For chunked encoded responses, it's best to iterate over the data using
382 :meth:`Response.iter_content() <requests.Response.iter_content>`. In
383 an ideal situation you'll have set ``stream=True`` on the request, in which
384 case you can iterate chunk-by-chunk by calling ``iter_content`` with a ``chunk_size``
385 parameter of ``None``. If you want to set a maximum size of the chunk,
386 you can set a ``chunk_size`` parameter to any integer.
387
388
389 .. _multipart:
390
391 POST Multiple Multipart-Encoded Files
392 -------------------------------------
393
394 You can send multiple files in one request. For example, suppose you want to
395 upload image files to an HTML form with a multiple file field 'images'::
396
397 <input type="file" name="images" multiple="true" required="true"/>
398
399 To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::
400
401 >>> 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.text
407 {
408 ...
409 'files': {'images': 'data:image/png;base64,iVBORw ....'}
410 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',
411 ...
412 }
413
414 .. warning:: It is strongly recommended that you open files in :ref:`binary
415 mode <tut-files>`. This is because Requests may attempt to provide
416 the ``Content-Length`` header for you, and if it does this value
417 will be set to the number of *bytes* in the file. Errors may occur
418 if you open the file in *text mode*.
419
420
421 .. _event-hooks:
422
423 Event Hooks
424 -----------
425
426 Requests has a hook system that you can use to manipulate portions of
427 the request process, or signal event handling.
428
429 Available hooks:
430
431 ``response``:
432 The response generated from a Request.
433
434
435 You can assign a hook function on a per-request basis by passing a
436 ``{hook_name: callback_function}`` dictionary to the ``hooks`` request
437 parameter::
438
439 hooks={'response': print_url}
440
441 That ``callback_function`` will receive a chunk of data as its first
442 argument.
443
444 ::
445
446 def print_url(r, *args, **kwargs):
447 print(r.url)
448
449 Your 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.
450
451 If the callback function returns a value, it is assumed that it is to
452 replace the data that was passed in. If the function doesn't return
453 anything, nothing else is affected.
454
455 ::
456
457 def record_hook(r, *args, **kwargs):
458 r.hook_called = True
459 return r
460
461 Let's print some request method arguments at runtime::
462
463 >>> requests.get('https://httpbin.org/', hooks={'response': print_url})
464 https://httpbin.org/
465 <Response [200]>
466
467 You can add multiple hooks to a single request. Let's call two hooks at once::
468
469 >>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})
470 https://httpbin.org/
471 >>> r.hook_called
472 True
473
474 You can also add hooks to a ``Session`` instance. Any hooks you add will then
475 be called on every request made to the session. For example::
476
477 >>> s = requests.Session()
478 >>> s.hooks['response'].append(print_url)
479 >>> s.get('https://httpbin.org/')
480 https://httpbin.org/
481 <Response [200]>
482
483 A ``Session`` can have multiple hooks, which will be called in the order
484 they are added.
485
486 .. _custom-auth:
487
488 Custom Authentication
489 ---------------------
490
491 Requests allows you to specify your own authentication mechanism.
492
493 Any callable which is passed as the ``auth`` argument to a request method will
494 have the opportunity to modify the request before it is dispatched.
495
496 Authentication implementations are subclasses of :class:`AuthBase <requests.auth.AuthBase>`,
497 and are easy to define. Requests provides two common authentication scheme
498 implementations in ``requests.auth``: :class:`HTTPBasicAuth <requests.auth.HTTPBasicAuth>` and
499 :class:`HTTPDigestAuth <requests.auth.HTTPDigestAuth>`.
500
501 Let's pretend that we have a web service that will only respond if the
502 ``X-Pizza`` header is set to a password value. Unlikely, but just go with it.
503
504 ::
505
506 from requests.auth import AuthBase
507
508 class PizzaAuth(AuthBase):
509 """Attaches HTTP Pizza Authentication to the given Request object."""
510 def __init__(self, username):
511 # setup any auth-related data here
512 self.username = username
513
514 def __call__(self, r):
515 # modify and return the request
516 r.headers['X-Pizza'] = self.username
517 return r
518
519 Then, we can make a request using our Pizza Auth::
520
521 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))
522 <Response [200]>
523
524 .. _streaming-requests:
525
526 Streaming Requests
527 ------------------
528
529 With :meth:`Response.iter_lines() <requests.Response.iter_lines>` you can easily
530 iterate over streaming APIs such as the `Twitter Streaming
531 API <https://dev.twitter.com/streaming/overview>`_. Simply
532 set ``stream`` to ``True`` and iterate over the response with
533 :meth:`~requests.Response.iter_lines()`::
534
535 import json
536 import requests
537
538 r = requests.get('https://httpbin.org/stream/20', stream=True)
539
540 for line in r.iter_lines():
541
542 # filter out keep-alive new lines
543 if line:
544 decoded_line = line.decode('utf-8')
545 print(json.loads(decoded_line))
546
547 When using `decode_unicode=True` with
548 :meth:`Response.iter_lines() <requests.Response.iter_lines>` or
549 :meth:`Response.iter_content() <requests.Response.iter_content>`, you'll want
550 to provide a fallback encoding in the event the server doesn't provide one::
551
552 r = requests.get('https://httpbin.org/stream/20', stream=True)
553
554 if r.encoding is None:
555 r.encoding = 'utf-8'
556
557 for line in r.iter_lines(decode_unicode=True):
558 if line:
559 print(json.loads(line))
560
561 .. warning::
562
563 :meth:`~requests.Response.iter_lines()` is not reentrant safe.
564 Calling this method multiple times causes some of the received data
565 being lost. In case you need to call it from multiple places, use
566 the resulting iterator object instead::
567
568 lines = r.iter_lines()
569 # Save the first line for later or just skip it
570
571 first_line = next(lines)
572
573 for line in lines:
574 print(line)
575
576 .. _proxies:
577
578 Proxies
579 -------
580
581 If you need to use a proxy, you can configure individual requests with the
582 ``proxies`` argument to any request method::
583
584 import requests
585
586 proxies = {
587 'http': 'http://10.10.1.10:3128',
588 'https': 'http://10.10.1.10:1080',
589 }
590
591 requests.get('http://example.org', proxies=proxies)
592
593 Alternatively you can configure it once for an entire
594 :class:`Session <requests.Session>`::
595
596 import requests
597
598 proxies = {
599 'http': 'http://10.10.1.10:3128',
600 'https': 'http://10.10.1.10:1080',
601 }
602 session = requests.Session()
603 session.proxies.update(proxies)
604
605 session.get('http://example.org')
606
607 .. warning:: Setting ``session.proxies`` may behave differently than expected.
608 Values provided will be overwritten by environmental proxies
609 (those returned by `urllib.request.getproxies <https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies>`_).
610 To ensure the use of proxies in the presence of environmental proxies,
611 explicitly specify the ``proxies`` argument on all individual requests as
612 initially explained above.
613
614 See `#2018 <https://github.com/psf/requests/issues/2018>`_ for details.
615
616 When the proxies configuration is not overridden per request as shown above,
617 Requests relies on the proxy configuration defined by standard
618 environment variables ``http_proxy``, ``https_proxy``, ``no_proxy``,
619 and ``all_proxy``. Uppercase variants of these variables are also supported.
620 You can therefore set them to configure Requests (only set the ones relevant
621 to your needs)::
622
623 $ export HTTP_PROXY="http://10.10.1.10:3128"
624 $ export HTTPS_PROXY="http://10.10.1.10:1080"
625 $ export ALL_PROXY="socks5://10.10.1.10:3434"
626
627 $ python
628 >>> import requests
629 >>> requests.get('http://example.org')
630
631 To use HTTP Basic Auth with your proxy, use the `http://user:password@host/`
632 syntax in any of the above configuration entries::
633
634 $ export HTTPS_PROXY="http://user:[email protected]:1080"
635
636 $ python
637 >>> proxies = {'http': 'http://user:[email protected]:3128/'}
638
639 .. warning:: Storing sensitive username and password information in an
640 environment variable or a version-controlled file is a security risk and is
641 highly discouraged.
642
643 To give a proxy for a specific scheme and host, use the
644 `scheme://hostname` form for the key. This will match for
645 any request to the given scheme and exact hostname.
646
647 ::
648
649 proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}
650
651 Note that proxy URLs must include the scheme.
652
653 Finally, note that using a proxy for https connections typically requires your
654 local machine to trust the proxy's root certificate. By default the list of
655 certificates trusted by Requests can be found with::
656
657 from requests.utils import DEFAULT_CA_BUNDLE_PATH
658 print(DEFAULT_CA_BUNDLE_PATH)
659
660 You override this default certificate bundle by setting the ``REQUESTS_CA_BUNDLE``
661 (or ``CURL_CA_BUNDLE``) environment variable to another file path::
662
663 $ export REQUESTS_CA_BUNDLE="/usr/local/myproxy_info/cacert.pem"
664 $ export https_proxy="http://10.10.1.10:1080"
665
666 $ python
667 >>> import requests
668 >>> requests.get('https://example.org')
669
670 .. _socks:
671
672 SOCKS
673 ^^^^^
674
675 .. versionadded:: 2.10.0
676
677 In addition to basic HTTP proxies, Requests also supports proxies using the
678 SOCKS protocol. This is an optional feature that requires that additional
679 third-party libraries be installed before use.
680
681 You can get the dependencies for this feature from ``pip``::
682
683 $ python -m pip install 'requests[socks]'
684
685 Once you've installed those dependencies, using a SOCKS proxy is just as easy
686 as using a HTTP one::
687
688 proxies = {
689 'http': 'socks5://user:pass@host:port',
690 'https': 'socks5://user:pass@host:port'
691 }
692
693 Using 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.
694
695 .. _compliance:
696
697 Compliance
698 ----------
699
700 Requests is intended to be compliant with all relevant specifications and
701 RFCs where that compliance will not cause difficulties for users. This
702 attention to the specification can lead to some behaviour that may seem
703 unusual to those not familiar with the relevant specification.
704
705 Encodings
706 ^^^^^^^^^
707
708 When you receive a response, Requests makes a guess at the encoding to
709 use for decoding the response when you access the :attr:`Response.text
710 <requests.Response.text>` attribute. Requests will first check for an
711 encoding in the HTTP header, and if none is present, will use
712 `charset_normalizer <https://pypi.org/project/charset_normalizer/>`_
713 or `chardet <https://github.com/chardet/chardet>`_ to attempt to
714 guess the encoding.
715
716 If ``chardet`` is installed, ``requests`` uses it, however for python3
717 ``chardet`` is no longer a mandatory dependency. The ``chardet``
718 library is an LGPL-licenced dependency and some users of requests
719 cannot depend on mandatory LGPL-licensed dependencies.
720
721 When you install ``requests`` without specifying ``[use_chardet_on_py3]`` extra,
722 and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``
723 (MIT-licensed) to guess the encoding.
724
725 The only time Requests will not guess the encoding is if no explicit charset
726 is present in the HTTP headers **and** the ``Content-Type``
727 header contains ``text``. In this situation, `RFC 2616
728 <https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1>`_ specifies
729 that the default charset must be ``ISO-8859-1``. Requests follows the
730 specification in this case. If you require a different encoding, you can
731 manually set the :attr:`Response.encoding <requests.Response.encoding>`
732 property, or use the raw :attr:`Response.content <requests.Response.content>`.
733
734 .. _http-verbs:
735
736 HTTP Verbs
737 ----------
738
739 Requests provides access to almost the full range of HTTP verbs: GET, OPTIONS,
740 HEAD, POST, PUT, PATCH and DELETE. The following provides detailed examples of
741 using these various verbs in Requests, using the GitHub API.
742
743 We will begin with the verb most commonly used: GET. HTTP GET is an idempotent
744 method that returns a resource from a given URL. As a result, it is the verb
745 you ought to use when attempting to retrieve data from a web location. An
746 example usage would be attempting to get information about a specific commit
747 from GitHub. Suppose we wanted commit ``a050faf`` on Requests. We would get it
748 like so::
749
750 >>> import requests
751 >>> r = requests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')
752
753 We should confirm that GitHub responded correctly. If it has, we want to work
754 out what type of content it is. Do this like so::
755
756 >>> if r.status_code == requests.codes.ok:
757 ... print(r.headers['content-type'])
758 ...
759 application/json; charset=utf-8
760
761 So, GitHub returns JSON. That's great, we can use the :meth:`r.json
762 <requests.Response.json>` method to parse it into Python objects.
763
764 ::
765
766 >>> commit_data = r.json()
767
768 >>> print(commit_data.keys())
769 ['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message']
770
771 >>> print(commit_data['committer'])
772 {'date': '2012-05-10T11:10:50-07:00', 'email': '[email protected]', 'name': 'Kenneth Reitz'}
773
774 >>> print(commit_data['message'])
775 makin' history
776
777 So far, so simple. Well, let's investigate the GitHub API a little bit. Now,
778 we could look at the documentation, but we might have a little more fun if we
779 use Requests instead. We can take advantage of the Requests OPTIONS verb to
780 see what kinds of HTTP methods are supported on the url we just used.
781
782 ::
783
784 >>> verbs = requests.options(r.url)
785 >>> verbs.status_code
786 500
787
788 Uh, what? That's unhelpful! Turns out GitHub, like many API providers, don't
789 actually implement the OPTIONS method. This is an annoying oversight, but it's
790 OK, we can just use the boring documentation. If GitHub had correctly
791 implemented OPTIONS, however, they should return the allowed methods in the
792 headers, e.g.
793
794 ::
795
796 >>> verbs = requests.options('http://a-good-website.com/api/cats')
797 >>> print(verbs.headers['allow'])
798 GET,HEAD,POST,OPTIONS
799
800 Turning to the documentation, we see that the only other method allowed for
801 commits is POST, which creates a new commit. As we're using the Requests repo,
802 we should probably avoid making ham-handed POSTS to it. Instead, let's play
803 with the Issues feature of GitHub.
804
805 This documentation was added in response to
806 `Issue #482 <https://github.com/psf/requests/issues/482>`_. Given that
807 this issue already exists, we will use it as an example. Let's start by getting it.
808
809 ::
810
811 >>> r = requests.get('https://api.github.com/repos/psf/requests/issues/482')
812 >>> r.status_code
813 200
814
815 >>> issue = json.loads(r.text)
816
817 >>> print(issue['title'])
818 Feature any http verb in docs
819
820 >>> print(issue['comments'])
821 3
822
823 Cool, we have three comments. Let's take a look at the last of them.
824
825 ::
826
827 >>> r = requests.get(r.url + '/comments')
828 >>> r.status_code
829 200
830
831 >>> comments = r.json()
832
833 >>> print(comments[0].keys())
834 ['body', 'url', 'created_at', 'updated_at', 'user', 'id']
835
836 >>> print(comments[2]['body'])
837 Probably in the "advanced" section
838
839 Well, that seems like a silly place. Let's post a comment telling the poster
840 that he's silly. Who is the poster, anyway?
841
842 ::
843
844 >>> print(comments[2]['user']['login'])
845 kennethreitz
846
847 OK, so let's tell this Kenneth guy that we think this example should go in the
848 quickstart guide instead. According to the GitHub API doc, the way to do this
849 is to POST to the thread. Let's do it.
850
851 ::
852
853 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it!"})
854 >>> url = u"https://api.github.com/repos/psf/requests/issues/482/comments"
855
856 >>> r = requests.post(url=url, data=body)
857 >>> r.status_code
858 404
859
860 Huh, that's weird. We probably need to authenticate. That'll be a pain, right?
861 Wrong. Requests makes it easy to use many forms of authentication, including
862 the very common Basic Auth.
863
864 ::
865
866 >>> from requests.auth import HTTPBasicAuth
867 >>> auth = HTTPBasicAuth('[email protected]', 'not_a_real_password')
868
869 >>> r = requests.post(url=url, data=body, auth=auth)
870 >>> r.status_code
871 201
872
873 >>> content = r.json()
874 >>> print(content['body'])
875 Sounds great! I'll get right on it.
876
877 Brilliant. Oh, wait, no! I meant to add that it would take me a while, because
878 I had to go feed my cat. If only I could edit this comment! Happily, GitHub
879 allows us to use another HTTP verb, PATCH, to edit this comment. Let's do
880 that.
881
882 ::
883
884 >>> print(content[u"id"])
885 5804413
886
887 >>> body = json.dumps({u"body": u"Sounds great! I'll get right on it once I feed my cat."})
888 >>> url = u"https://api.github.com/repos/psf/requests/issues/comments/5804413"
889
890 >>> r = requests.patch(url=url, data=body, auth=auth)
891 >>> r.status_code
892 200
893
894 Excellent. Now, just to torture this Kenneth guy, I've decided to let him
895 sweat and not tell him that I'm working on this. That means I want to delete
896 this comment. GitHub lets us delete comments using the incredibly aptly named
897 DELETE method. Let's get rid of it.
898
899 ::
900
901 >>> r = requests.delete(url=url, auth=auth)
902 >>> r.status_code
903 204
904 >>> r.headers['status']
905 '204 No Content'
906
907 Excellent. All gone. The last thing I want to know is how much of my ratelimit
908 I've used. Let's find out. GitHub sends that information in the headers, so
909 rather than download the whole page I'll send a HEAD request to get the
910 headers.
911
912 ::
913
914 >>> r = requests.head(url=url, auth=auth)
915 >>> print(r.headers)
916 ...
917 'x-ratelimit-remaining': '4995'
918 'x-ratelimit-limit': '5000'
919 ...
920
921 Excellent. Time to write a Python program that abuses the GitHub API in all
922 kinds of exciting ways, 4995 more times.
923
924 .. _custom-verbs:
925
926 Custom Verbs
927 ------------
928
929 From time to time you may be working with a server that, for whatever reason,
930 allows use or even requires use of HTTP verbs not covered above. One example of
931 this would be the MKCOL method some WEBDAV servers use. Do not fret, these can
932 still be used with Requests. These make use of the built-in ``.request``
933 method. For example::
934
935 >>> r = requests.request('MKCOL', url, data=data)
936 >>> r.status_code
937 200 # Assuming your call was correct
938
939 Utilising this, you can make use of any method verb that your server allows.
940
941
942 .. _link-headers:
943
944 Link Headers
945 ------------
946
947 Many HTTP APIs feature Link headers. They make APIs more self describing and
948 discoverable.
949
950 GitHub uses these for `pagination <https://docs.github.com/en/rest/guides/using-pagination-in-the-rest-api>`_
951 in their API, for example::
952
953 >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'
954 >>> r = requests.head(url=url)
955 >>> r.headers['link']
956 '<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"'
957
958 Requests will automatically parse these link headers and make them easily consumable::
959
960 >>> r.links["next"]
961 {'url': 'https://api.github.com/users/kennethreitz/repos?page=2&per_page=10', 'rel': 'next'}
962
963 >>> r.links["last"]
964 {'url': 'https://api.github.com/users/kennethreitz/repos?page=7&per_page=10', 'rel': 'last'}
965
966 .. _transport-adapters:
967
968 Transport Adapters
969 ------------------
970
971 As of v1.0.0, Requests has moved to a modular internal design using Transport
972 Adapters. These objects provide a mechanism to define interaction methods for an
973 HTTP service. In particular, they allow you to apply per-service configuration.
974
975 Requests ships with a single Transport Adapter, the :class:`HTTPAdapter
976 <requests.adapters.HTTPAdapter>`. This adapter provides the default Requests
977 interaction with HTTP and HTTPS using the powerful `urllib3`_ library. Whenever
978 a Requests :class:`Session <requests.Session>` is initialized, one of these is
979 attached to the :class:`Session <requests.Session>` object for HTTP, and one
980 for HTTPS.
981
982 Requests enables users to create and use their own Transport Adapters that
983 provide specific functionality. Once created, a Transport Adapter can be
984 mounted to a Session object, along with an indication of which web services
985 it should apply to.
986
987 ::
988
989 >>> s = requests.Session()
990 >>> s.mount('https://github.com/', MyAdapter())
991
992 The mount call registers a specific instance of a Transport Adapter to a
993 prefix. Once mounted, any HTTP request made using that session whose URL starts
994 with the given prefix will use the given Transport Adapter.
995
996 .. note:: The adapter will be chosen based on a longest prefix match. Be mindful
997 prefixes such as ``http://localhost`` will also match ``http://localhost.other.com``
998 or ``http://[email protected]``. It's recommended to terminate full hostnames with a ``/``.
999
1000 Many of the details of implementing a Transport Adapter are beyond the scope of
1001 this documentation, but take a look at the next example for a simple SSL use-
1002 case. For more than that, you might look at subclassing the
1003 :class:`BaseAdapter <requests.adapters.BaseAdapter>`.
1004
1005 Example: Specific SSL Version
1006 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1007
1008 The Requests team has made a specific choice to use whatever SSL version is
1009 default in the underlying library (`urllib3`_). Normally this is fine, but from
1010 time to time, you might find yourself needing to connect to a service-endpoint
1011 that uses a version that isn't compatible with the default.
1012
1013 You can use Transport Adapters for this by taking most of the existing
1014 implementation of HTTPAdapter, and adding a parameter *ssl_version* that gets
1015 passed-through to `urllib3`. We'll make a Transport Adapter that instructs the
1016 library to use SSLv3::
1017
1018 import ssl
1019 from urllib3.poolmanager import PoolManager
1020
1021 from requests.adapters import HTTPAdapter
1022
1023
1024 class Ssl3HttpAdapter(HTTPAdapter):
1025 """"Transport adapter" that allows us to use SSLv3."""
1026
1027 def init_poolmanager(self, connections, maxsize, block=False):
1028 self.poolmanager = PoolManager(
1029 num_pools=connections, maxsize=maxsize,
1030 block=block, ssl_version=ssl.PROTOCOL_SSLv3)
1031
1032 Example: Automatic Retries
1033 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1034
1035 By default, Requests does not retry failed connections. However, it is possible
1036 to implement automatic retries with a powerful array of features, including
1037 backoff, within a Requests :class:`Session <requests.Session>` using the
1038 `urllib3.util.Retry`_ class::
1039
1040 from urllib3.util import Retry
1041 from requests import Session
1042 from requests.adapters import HTTPAdapter
1043
1044 s = Session()
1045 retries = Retry(
1046 total=3,
1047 backoff_factor=0.1,
1048 status_forcelist=[502, 503, 504],
1049 allowed_methods={'POST'},
1050 )
1051 s.mount('https://', HTTPAdapter(max_retries=retries))
1052
1053 .. _`urllib3`: https://github.com/urllib3/urllib3
1054 .. _`urllib3.util.Retry`: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry
1055
1056 .. _blocking-or-nonblocking:
1057
1058 Blocking Or Non-Blocking?
1059 -------------------------
1060
1061 With the default Transport Adapter in place, Requests does not provide any kind
1062 of non-blocking IO. The :attr:`Response.content <requests.Response.content>`
1063 property will block until the entire response has been downloaded. If
1064 you require more granularity, the streaming features of the library (see
1065 :ref:`streaming-requests`) allow you to retrieve smaller quantities of the
1066 response at a time. However, these calls will still block.
1067
1068 If you are concerned about the use of blocking IO, there are lots of projects
1069 out there that combine Requests with one of Python's asynchronicity frameworks.
1070 Some excellent examples are `requests-threads`_, `grequests`_, `requests-futures`_, and `httpx`_.
1071
1072 .. _`requests-threads`: https://github.com/requests/requests-threads
1073 .. _`grequests`: https://github.com/spyoungtech/grequests
1074 .. _`requests-futures`: https://github.com/ross/requests-futures
1075 .. _`httpx`: https://github.com/encode/httpx
1076
1077 Header Ordering
1078 ---------------
1079
1080 In 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.
1081
1082 If 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.
1083
1084 .. _timeouts:
1085
1086 Timeouts
1087 --------
1088
1089 Most requests to external servers should have a timeout attached, in case the
1090 server is not responding in a timely manner. By default, requests do not time
1091 out unless a timeout value is set explicitly. Without a timeout, your code may
1092 hang for minutes or more.
1093
1094 The **connect** timeout is the number of seconds Requests will wait for your
1095 client to establish a connection to a remote machine (corresponding to the
1096 `connect()`_) call on the socket. It's a good practice to set connect timeouts
1097 to slightly larger than a multiple of 3, which is the default `TCP packet
1098 retransmission window <https://datatracker.ietf.org/doc/html/rfc2988>`_.
1099
1100 Once your client has connected to the server and sent the HTTP request, the
1101 **read** timeout is the number of seconds the client will wait for the server
1102 to send a response. (Specifically, it's the number of seconds that the client
1103 will wait *between* bytes sent from the server. In 99.9% of cases, this is the
1104 time before the server sends the first byte).
1105
1106 If you specify a single value for the timeout, like this::
1107
1108 r = requests.get('https://github.com', timeout=5)
1109
1110 The timeout value will be applied to both the ``connect`` and the ``read``
1111 timeouts. Specify a tuple if you would like to set the values separately::
1112
1113 r = requests.get('https://github.com', timeout=(3.05, 27))
1114
1115 If the remote server is very slow, you can tell Requests to wait forever for
1116 a response, by passing None as a timeout value and then retrieving a cup of
1117 coffee.
1118
1119 ::
1120
1121 r = requests.get('https://github.com', timeout=None)
1122
1123 .. note:: The connect timeout applies to each connection attempt to an IP address.
1124 If multiple addresses exist for a domain name, the underlying ``urllib3`` will
1125 try each address sequentially until one successfully connects.
1126 This may lead to an effective total connection timeout *multiple* times longer
1127 than the specified time, e.g. an unresponsive server having both IPv4 and IPv6
1128 addresses will have its perceived timeout *doubled*, so take that into account
1129 when setting the connection timeout.
1130 .. note:: Neither the connect nor read timeouts are `wall clock`_. This means
1131 that if you start a request, and look at the time, and then look at
1132 the time when the request finishes or times out, the real-world time
1133 may be greater than what you specified.
1134
1135
1136 .. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time
1137 .. _`connect()`: https://linux.die.net/man/2/connect