Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/requests_toolbelt/adapters/ssl.py: 62%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

16 statements  

1# -*- coding: utf-8 -*- 

2""" 

3 

4requests_toolbelt.ssl_adapter 

5============================= 

6 

7This file contains an implementation of the SSLAdapter originally demonstrated 

8in this blog post: 

9https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ 

10 

11""" 

12import requests 

13 

14from requests.adapters import HTTPAdapter 

15 

16from .._compat import poolmanager 

17 

18 

19class SSLAdapter(HTTPAdapter): 

20 """ 

21 A HTTPS Adapter for Python Requests that allows the choice of the SSL/TLS 

22 version negotiated by Requests. This can be used either to enforce the 

23 choice of high-security TLS versions (where supported), or to work around 

24 misbehaving servers that fail to correctly negotiate the default TLS 

25 version being offered. 

26 

27 Example usage: 

28 

29 >>> import requests 

30 >>> import ssl 

31 >>> from requests_toolbelt import SSLAdapter 

32 >>> s = requests.Session() 

33 >>> s.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1)) 

34 

35 You can replace the chosen protocol with any that are available in the 

36 default Python SSL module. All subsequent requests that match the adapter 

37 prefix will use the chosen SSL version instead of the default. 

38 

39 This adapter will also attempt to change the SSL/TLS version negotiated by 

40 Requests when using a proxy. However, this may not always be possible: 

41 prior to Requests v2.4.0 the adapter did not have access to the proxy setup 

42 code. In earlier versions of Requests, this adapter will not function 

43 properly when used with proxies. 

44 """ 

45 

46 __attrs__ = HTTPAdapter.__attrs__ + ['ssl_version'] 

47 

48 def __init__(self, ssl_version=None, **kwargs): 

49 self.ssl_version = ssl_version 

50 

51 super(SSLAdapter, self).__init__(**kwargs) 

52 

53 def init_poolmanager(self, connections, maxsize, block=False): 

54 self.poolmanager = poolmanager.PoolManager( 

55 num_pools=connections, 

56 maxsize=maxsize, 

57 block=block, 

58 ssl_version=self.ssl_version) 

59 

60 if requests.__build__ >= 0x020400: 

61 # Earlier versions of requests either don't have this method or, worse, 

62 # don't allow passing arbitrary keyword arguments. As a result, only 

63 # conditionally define this method. 

64 def proxy_manager_for(self, *args, **kwargs): 

65 kwargs['ssl_version'] = self.ssl_version 

66 return super(SSLAdapter, self).proxy_manager_for(*args, **kwargs)