Debian Codegraph @

docs/advanced-usage.rst

raw
1 Advanced Usage
2 ==============
3
4 .. currentmodule:: urllib3
5
6
7 Customizing Pool Behavior
8 -------------------------
9
10 The :class:`~poolmanager.PoolManager` class automatically handles creating
11 :class:`~connectionpool.ConnectionPool` instances for each host as needed. By
12 default, it will keep a maximum of 10 :class:`~connectionpool.ConnectionPool`
13 instances. If you're making requests to many different hosts it might improve
14 performance to increase this number.
15
16 .. code-block:: python
17
18 import urllib3
19
20 http = urllib3.PoolManager(num_pools=50)
21
22 However, keep in mind that this does increase memory and socket consumption.
23
24 Similarly, the :class:`~connectionpool.ConnectionPool` class keeps a pool
25 of individual :class:`~connection.HTTPConnection` instances. These connections
26 are used during an individual request and returned to the pool when the request
27 is complete. By default only one connection will be saved for re-use. If you
28 are making many requests to the same host simultaneously it might improve
29 performance to increase this number.
30
31 .. code-block:: python
32
33 import urllib3
34
35 http = urllib3.PoolManager(maxsize=10)
36 # Alternatively
37 pool = urllib3.HTTPConnectionPool("google.com", maxsize=10)
38
39 The behavior of the pooling for :class:`~connectionpool.ConnectionPool` is
40 different from :class:`~poolmanager.PoolManager`. By default, if a new
41 request is made and there is no free connection in the pool then a new
42 connection will be created. However, this connection will not be saved if more
43 than ``maxsize`` connections exist. This means that ``maxsize`` does not
44 determine the maximum number of connections that can be open to a particular
45 host, just the maximum number of connections to keep in the pool. However, if you specify ``block=True`` then there can be at most ``maxsize`` connections
46 open to a particular host.
47
48 .. code-block:: python
49
50 http = urllib3.PoolManager(maxsize=10, block=True)
51
52 # Alternatively
53 pool = urllib3.HTTPConnectionPool("google.com", maxsize=10, block=True)
54
55 Any new requests will block until a connection is available from the pool.
56 This is a great way to prevent flooding a host with too many connections in
57 multi-threaded applications.
58
59 .. _stream:
60 .. _streaming_and_io:
61
62 Streaming and I/O
63 -----------------
64
65 When using ``preload_content=True`` (the default setting) the
66 response body will be read immediately into memory and the HTTP connection
67 will be released back into the pool without manual intervention.
68
69 However, when dealing with responses of large or unknown length,
70 it's often better to stream the response
71 content using ``preload_content=False``. Setting ``preload_content`` to ``False`` means
72 that urllib3 will only read from the socket when data is requested.
73
74 .. note:: When using ``preload_content=False``, you need to manually release
75 the HTTP connection back to the connection pool so that it can be re-used.
76 To ensure the HTTP connection is in a valid state before being re-used
77 all data should be read off the wire.
78
79 You can call the :meth:`~response.HTTPResponse.drain_conn` to throw away
80 unread data still on the wire. This call isn't necessary if data has already
81 been completely read from the response.
82
83 After all data is read you can call :meth:`~response.HTTPResponse.release_conn`
84 to release the connection into the pool.
85
86 You can call the :meth:`~response.HTTPResponse.close` to close the connection,
87 but this call doesn’t return the connection to the pool, throws away the unread
88 data on the wire, and leaves the connection in an undefined protocol state.
89 This is desirable if you prefer not reading data from the socket to re-using the
90 HTTP connection.
91
92 :meth:`~response.HTTPResponse.stream` lets you iterate over chunks of the response content.
93
94 .. code-block:: python
95
96 import urllib3
97
98 resp = urllib3.request(
99 "GET",
100 "https://httpbin.org/bytes/1024",
101 preload_content=False
102 )
103
104 for chunk in resp.stream(32):
105 print(chunk)
106 # b"\x9e\xa97'\x8e\x1eT ....
107
108 resp.release_conn()
109
110 However, you can also treat the :class:`~response.HTTPResponse` instance as
111 a file-like object. This allows you to do buffering:
112
113 .. code-block:: python
114
115 import urllib3
116
117 resp = urllib3.request(
118 "GET",
119 "https://httpbin.org/bytes/1024",
120 preload_content=False
121 )
122
123 print(resp.read(4))
124 # b"\x88\x1f\x8b\xe5"
125
126 Calls to :meth:`~response.HTTPResponse.read()` will block until more response
127 data is available.
128
129 .. code-block:: python
130
131 import io
132 import urllib3
133
134 resp = urllib3.request(
135 "GET",
136 "https://httpbin.org/bytes/1024",
137 preload_content=False
138 )
139
140 reader = io.BufferedReader(resp, 8)
141 print(reader.read(4))
142 # b"\xbf\x9c\xd6"
143
144 resp.release_conn()
145
146 You can use this file-like object to do things like decode the content using
147 :mod:`codecs`:
148
149 .. code-block:: python
150
151 import codecs
152 import json
153 import urllib3
154
155 reader = codecs.getreader("utf-8")
156
157 resp = urllib3.request(
158 "GET",
159 "https://httpbin.org/ip",
160 preload_content=False
161 )
162
163 print(json.load(reader(resp)))
164 # {"origin": "127.0.0.1"}
165
166 resp.release_conn()
167
168 .. _proxies:
169
170 Proxies
171 -------
172
173 You can use :class:`~poolmanager.ProxyManager` to tunnel requests through an
174 HTTP proxy:
175
176 .. code-block:: python
177
178 import urllib3
179
180 proxy = urllib3.ProxyManager("https://localhost:3128/")
181 proxy.request("GET", "https://google.com/")
182
183 The usage of :class:`~poolmanager.ProxyManager` is the same as
184 :class:`~poolmanager.PoolManager`.
185
186 You can connect to a proxy using HTTP, HTTPS or SOCKS. urllib3's behavior will
187 be different depending on the type of proxy you selected and the destination
188 you're contacting.
189
190 HTTP and HTTPS Proxies
191 ~~~~~~~~~~~~~~~~~~~~~~
192
193 Both HTTP/HTTPS proxies support HTTP and HTTPS destinations. The only
194 difference between them is if you need to establish a TLS connection to the
195 proxy first. You can specify which proxy you need to contact by specifying the
196 proper proxy scheme. (i.e ``http://`` or ``https://``)
197
198 urllib3's behavior will be different depending on your proxy and destination:
199
200 * HTTP proxy + HTTP destination
201 Your request will be forwarded with the `absolute URI
202 <https://datatracker.ietf.org/doc/html/rfc9112#name-absolute-form>`_.
203
204 * HTTP proxy + HTTPS destination
205 A TCP tunnel will be established with a `HTTP
206 CONNECT <https://datatracker.ietf.org/doc/html/rfc9110#name-connect>`_. Afterward a
207 TLS connection will be established with the destination and your request
208 will be sent.
209
210 * HTTPS proxy + HTTP destination
211 A TLS connection will be established to the proxy and later your request
212 will be forwarded with the `absolute URI
213 <https://datatracker.ietf.org/doc/html/rfc9112#name-absolute-form>`_.
214
215 * HTTPS proxy + HTTPS destination
216 A TLS-in-TLS tunnel will be established. An initial TLS connection will be
217 established to the proxy, then an `HTTP CONNECT
218 <https://datatracker.ietf.org/doc/html/rfc9110#name-connect>`_ will be sent to
219 establish a TCP connection to the destination and finally a second TLS
220 connection will be established to the destination. You can customize the
221 :class:`ssl.SSLContext` used for the proxy TLS connection through the
222 ``proxy_ssl_context`` argument of the :class:`~poolmanager.ProxyManager`
223 class.
224
225 For HTTPS proxies we also support forwarding your requests to HTTPS destinations with
226 an `absolute URI <https://datatracker.ietf.org/doc/html/rfc9112#name-absolute-form>`_ if the
227 ``use_forwarding_for_https`` argument is set to ``True``. We strongly recommend you
228 **only use this option with trusted or corporate proxies** as the proxy will have
229 full visibility of your requests.
230
231 .. _https_proxy_error_http_proxy:
232
233 Your proxy appears to only use HTTP and not HTTPS
234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
235
236 If you're receiving the :class:`~urllib3.exceptions.ProxyError` and it mentions
237 your proxy only speaks HTTP and not HTTPS here's what to do to solve your issue:
238
239 If you're using ``urllib3`` directly, make sure the URL you're passing into :class:`urllib3.ProxyManager`
240 starts with ``http://`` instead of ``https://``:
241
242 .. code-block:: python
243
244 # Do this:
245 http = urllib3.ProxyManager("http://...")
246
247 # Not this:
248 http = urllib3.ProxyManager("https://...")
249
250 If instead you're using ``urllib3`` through another library like Requests
251 there are multiple ways your proxy could be mis-configured. You need to figure out
252 where the configuration isn't correct and make the fix there. Some common places
253 to look are environment variables like ``HTTP_PROXY``, ``HTTPS_PROXY``, and ``ALL_PROXY``.
254
255 Ensure that the values for all of these environment variables starts with ``http://``
256 and not ``https://``:
257
258 .. code-block:: bash
259
260 # Check your existing environment variables in bash
261 $ env | grep "_PROXY"
262 HTTP_PROXY=http://127.0.0.1:8888
263 HTTPS_PROXY=https://127.0.0.1:8888 # <--- This setting is the problem!
264
265 # Make the fix in your current session and test your script
266 $ export HTTPS_PROXY="http://127.0.0.1:8888"
267 $ python test-proxy.py # This should now pass.
268
269 # Persist your change in your shell 'profile' (~/.bashrc, ~/.profile, ~/.bash_profile, etc)
270 # You may need to logout and log back in to ensure this works across all programs.
271 $ vim ~/.bashrc
272
273 If you're on Windows or macOS your proxy may be getting set at a system level.
274 To check this first ensure that the above environment variables aren't set
275 then run the following:
276
277 .. code-block:: bash
278
279 $ python -c 'import urllib.request; print(urllib.request.getproxies())'
280
281 If the output of the above command isn't empty and looks like this:
282
283 .. code-block:: python
284
285 {
286 "http": "http://127.0.0.1:8888",
287 "https": "https://127.0.0.1:8888" # <--- This setting is the problem!
288 }
289
290 Search how to configure proxies on your operating system and change the ``https://...`` URL into ``http://``.
291 After you make the change the return value of ``urllib.request.getproxies()`` should be:
292
293 .. code-block:: python
294
295 { # Everything is good here! :)
296 "http": "http://127.0.0.1:8888",
297 "https": "http://127.0.0.1:8888"
298 }
299
300 If you still can't figure out how to configure your proxy after all these steps
301 please `join our community Discord <https://discord.gg/urllib3>`_ and we'll try to help you with your issue.
302
303 SOCKS Proxies
304 ~~~~~~~~~~~~~
305
306
307 For SOCKS, you can use :class:`~contrib.socks.SOCKSProxyManager` to connect to
308 SOCKS4 or SOCKS5 proxies. In order to use SOCKS proxies you will need to
309 install `PySocks <https://pypi.org/project/PySocks/>`_ or install urllib3 with
310 the ``socks`` extra:
311
312 .. code-block:: bash
313
314 python -m pip install urllib3[socks]
315
316 Once PySocks is installed, you can use
317 :class:`~contrib.socks.SOCKSProxyManager`:
318
319 .. code-block:: python
320
321 from urllib3.contrib.socks import SOCKSProxyManager
322
323 proxy = SOCKSProxyManager("socks5h://localhost:8889/")
324 proxy.request("GET", "https://google.com/")
325
326 .. note::
327 It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in
328 your ``proxy_url`` to ensure that DNS resolution is done from the remote
329 server instead of client-side when connecting to a domain name.
330
331 .. _ssl_custom:
332 .. _custom_ssl_certificates:
333
334 Custom TLS Certificates
335 -----------------------
336
337 Instead of using `certifi <https://certifi.io/>`_ you can provide your
338 own certificate authority bundle. This is useful for cases where you've
339 generated your own certificates or when you're using a private certificate
340 authority. Just provide the full path to the certificate bundle when creating a
341 :class:`~poolmanager.PoolManager`:
342
343 .. code-block:: python
344
345 import urllib3
346
347 http = urllib3.PoolManager(
348 cert_reqs="CERT_REQUIRED",
349 ca_certs="/path/to/your/certificate_bundle"
350 )
351 resp = http.request("GET", "https://example.com")
352
353 When you specify your own certificate bundle only requests that can be
354 verified with that bundle will succeed. It's recommended to use a separate
355 :class:`~poolmanager.PoolManager` to make requests to URLs that do not need
356 the custom certificate.
357
358 .. _sni_custom:
359
360 Custom SNI Hostname
361 -------------------
362
363 If you want to create a connection to a host over HTTPS which uses SNI, there
364 are two places where the hostname is expected. It must be included in the Host
365 header sent, so that the server will know which host is being requested. The
366 hostname should also match the certificate served by the server, which is
367 checked by urllib3.
368
369 Normally, urllib3 takes care of setting and checking these values for you when
370 you connect to a host by name. However, it's sometimes useful to set a
371 connection's expected Host header and certificate hostname (subject),
372 especially when you are connecting without using name resolution. For example,
373 you could connect to a server by IP using HTTPS like so:
374
375 .. code-block:: python
376
377 import urllib3
378
379 pool = urllib3.HTTPSConnectionPool(
380 "104.154.89.105",
381 server_hostname="badssl.com"
382 )
383 pool.request(
384 "GET",
385 "/",
386 headers={"Host": "badssl.com"},
387 assert_same_host=False
388 )
389
390
391 Note that when you use a connection in this way, you must specify
392 ``assert_same_host=False``.
393
394 This is useful when DNS resolution for ``example.org`` does not match the
395 address that you would like to use. The IP may be for a private interface, or
396 you may want to use a specific host under round-robin DNS.
397
398
399 .. _assert_hostname:
400
401 Verifying TLS against a different host
402 --------------------------------------
403
404 If the server you're connecting to presents a different certificate than the
405 hostname or the SNI hostname, you can use ``assert_hostname``:
406
407 .. code-block:: python
408
409 import urllib3
410
411 pool = urllib3.HTTPSConnectionPool(
412 "wrong.host.badssl.com",
413 assert_hostname="badssl.com",
414 )
415 pool.request("GET", "/")
416
417
418 .. _ssl_client:
419
420 Client Certificates
421 -------------------
422
423 You can also specify a client certificate. This is useful when both the server
424 and the client need to verify each other's identity. Typically these
425 certificates are issued from the same authority. To use a client certificate,
426 provide the full path when creating a :class:`~poolmanager.PoolManager`:
427
428 .. code-block:: python
429
430 http = urllib3.PoolManager(
431 cert_file="/path/to/your/client_cert.pem",
432 cert_reqs="CERT_REQUIRED",
433 ca_certs="/path/to/your/certificate_bundle"
434 )
435
436 If you have an encrypted client certificate private key you can use
437 the ``key_password`` parameter to specify a password to decrypt the key.
438
439 .. code-block:: python
440
441 http = urllib3.PoolManager(
442 cert_file="/path/to/your/client_cert.pem",
443 cert_reqs="CERT_REQUIRED",
444 key_file="/path/to/your/client.key",
445 key_password="keyfile_password"
446 )
447
448 If your key isn't encrypted the ``key_password`` parameter isn't required.
449
450 TLS minimum and maximum versions
451 --------------------------------
452
453 When the configured TLS versions by urllib3 aren't compatible with the TLS versions that
454 the server is willing to use you'll likely see an error like this one:
455
456 .. code-block::
457
458 SSLError(1, '[SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:1124)')
459
460 Starting in v2.0 by default urllib3 uses TLS 1.2 and later so servers that only support TLS 1.1
461 or earlier will not work by default with urllib3.
462
463 To fix the issue you'll need to use the ``ssl_minimum_version`` option along with the `TLSVersion enum`_
464 in the standard library ``ssl`` module to configure urllib3 to accept a wider range of TLS versions.
465
466 For the best security it's a good idea to set this value to the version of TLS that's being used by the
467 server. For example if the server requires TLS 1.0 you'd configure urllib3 like so:
468
469 .. code-block:: python
470
471 import ssl
472 import urllib3
473
474 http = urllib3.PoolManager(
475 ssl_minimum_version=ssl.TLSVersion.TLSv1
476 )
477 # This request works!
478 resp = http.request("GET", "https://tls-v1-0.badssl.com:1010")
479
480 .. _TLSVersion enum: https://docs.python.org/3/library/ssl.html#ssl.TLSVersion
481
482 .. _ssl_mac:
483 .. _certificate_validation_and_mac_os_x:
484
485 Certificate Validation and macOS
486 --------------------------------
487
488 Apple-provided Python and OpenSSL libraries contain a patches that make them
489 automatically check the system keychain's certificates. This can be
490 surprising if you specify custom certificates and see requests unexpectedly
491 succeed. For example, if you are specifying your own certificate for validation
492 and the server presents a different certificate you would expect the connection
493 to fail. However, if that server presents a certificate that is in the system
494 keychain then the connection will succeed.
495
496 `This article <https://hynek.me/articles/apple-openssl-verification-surprises/>`_
497 has more in-depth analysis and explanation.
498
499 .. _ssl_warnings:
500
501 TLS Warnings
502 ------------
503
504 urllib3 will issue several different warnings based on the level of certificate
505 verification support. These warnings indicate particular situations and can
506 be resolved in different ways.
507
508 * :class:`~exceptions.InsecureRequestWarning`
509 This happens when a request is made to an HTTPS URL without certificate
510 verification enabled. Follow the :ref:`certificate verification <ssl>`
511 guide to resolve this warning.
512
513 .. _disable_ssl_warnings:
514
515 Making unverified HTTPS requests is **strongly** discouraged, however, if you
516 understand the risks and wish to disable these warnings, you can use :func:`~urllib3.disable_warnings`:
517
518 .. code-block:: python
519
520 import urllib3
521
522 urllib3.disable_warnings()
523
524 Alternatively you can capture the warnings with the standard :mod:`logging` module:
525
526 .. code-block:: python
527
528 logging.captureWarnings(True)
529
530 Finally, you can suppress the warnings at the interpreter level by setting the
531 ``PYTHONWARNINGS`` environment variable or by using the
532 `-W flag <https://docs.python.org/3/using/cmdline.html#cmdoption-w>`_.
533
534 Brotli Encoding
535 ---------------
536
537 Brotli is a compression algorithm created by Google with better compression
538 than gzip and deflate and is supported by urllib3 if the
539 `Brotli <https://pypi.org/project/brotli/>`_ package or
540 `brotlicffi <https://github.com/python-hyper/brotlicffi>`_ package is installed.
541 You may also request the package be installed via the ``urllib3[brotli]`` extra:
542
543 .. code-block:: bash
544
545 $ python -m pip install urllib3[brotli]
546
547 Here's an example using brotli encoding via the ``Accept-Encoding`` header:
548
549 .. code-block:: python
550
551 import urllib3
552
553 urllib3.request(
554 "GET",
555 "https://www.google.com/",
556 headers={"Accept-Encoding": "br"}
557 )
558
559 Zstandard Encoding
560 ------------------
561
562 `Zstandard <https://datatracker.ietf.org/doc/html/rfc8878>`_
563 is a compression algorithm created by Facebook with better compression
564 than brotli, gzip and deflate (see `benchmarks <https://facebook.github.io/zstd/#benchmarks>`_)
565 and is supported by urllib3 in Python 3.14+ using the `compression.zstd <https://peps.python.org/pep-0784/>`_ standard library module
566 and for Python 3.13 and earlier if the `backports.zstd package <https://pypi.org/project/backports.zstd/>`_ is installed.
567 You may also request the package be installed via the ``urllib3[zstd]`` extra:
568
569 .. code-block:: bash
570
571 # This is only necessary on Python 3.13 and earlier.
572 # Otherwise zstandard support is included in the Python standard library.
573 $ python -m pip install urllib3[zstd]
574
575 .. note::
576
577 Zstandard support in urllib3 requires using v0.18.0 or later of the ``zstandard`` package.
578 If the version installed is less than v0.18.0 then Zstandard support won't be enabled.
579
580 Here's an example using zstd encoding via the ``Accept-Encoding`` header:
581
582 .. code-block:: python
583
584 import urllib3
585
586 urllib3.request(
587 "GET",
588 "https://www.facebook.com/",
589 headers={"Accept-Encoding": "zstd"}
590 )
591
592
593 Decrypting Captured TLS Sessions with Wireshark
594 -----------------------------------------------
595 Python supports logging of TLS pre-master secrets.
596 With these secrets tools like `Wireshark <https://wireshark.org>`_ can decrypt captured
597 network traffic.
598
599 To enable this simply define environment variable `SSLKEYLOGFILE`:
600
601 .. code-block:: bash
602
603 export SSLKEYLOGFILE=/path/to/keylogfile.txt
604
605 Then configure the key logfile in `Wireshark <https://wireshark.org>`_, see
606 `Wireshark TLS Decryption <https://wiki.wireshark.org/TLS#TLS_Decryption>`_ for instructions.
607
608 Custom SSL Contexts
609 -------------------
610
611 You can exercise fine-grained control over the urllib3 SSL configuration by
612 providing a :class:`ssl.SSLContext <python:ssl.SSLContext>` object. For purposes
613 of compatibility, we recommend you obtain one from
614 :func:`~urllib3.util.create_urllib3_context`.
615
616 Once you have a context object, you can mutate it to achieve whatever effect
617 you'd like. For example, the code below loads the default SSL certificates, sets
618 the :data:`ssl.OP_ENABLE_MIDDLEBOX_COMPAT<python:ssl.OP_ENABLE_MIDDLEBOX_COMPAT>`
619 flag that isn't set by default, and then makes a HTTPS request:
620
621 .. code-block:: python
622
623 import ssl
624
625 from urllib3 import PoolManager
626 from urllib3.util import create_urllib3_context
627
628 ctx = create_urllib3_context()
629 ctx.load_default_certs()
630 ctx.options |= ssl.OP_ENABLE_MIDDLEBOX_COMPAT
631
632 with PoolManager(ssl_context=ctx) as pool:
633 pool.request("GET", "https://www.google.com/")
634
635 Note that this is different from passing an ``options`` argument to
636 :func:`~urllib3.util.create_urllib3_context` because we don't overwrite
637 the default options: we only add a new one.