19
19
"""This module contains methods to make POST and GET requests"""
20
20
21
21
import json
22
+ import os
22
23
import socket
23
24
import logging
24
25
31
32
32
33
_CON_POOL = None
33
34
""":type: urllib3.PoolManager"""
35
+ _CON_POOL_PROXY = None
36
+ _CON_POOL_PROXY_KWARGS = {}
34
37
CON_POOL_SIZE = 1
35
38
36
39
logging .getLogger ('urllib3' ).setLevel (logging .WARNING )
37
40
38
41
39
42
def _get_con_pool ():
40
- global _CON_POOL
41
-
42
43
if _CON_POOL is not None :
43
44
return _CON_POOL
44
45
45
- _CON_POOL = urllib3 .PoolManager (maxsize = CON_POOL_SIZE ,
46
- cert_reqs = 'CERT_REQUIRED' ,
47
- ca_certs = certifi .where (),
48
- socket_options = HTTPConnection .default_socket_options + [
49
- (socket .SOL_SOCKET , socket .SO_KEEPALIVE , 1 ),
50
- ])
46
+ _init_con_pool ()
51
47
return _CON_POOL
52
48
53
49
50
+ def _init_con_pool ():
51
+ global _CON_POOL
52
+ kwargs = dict (maxsize = CON_POOL_SIZE ,
53
+ cert_reqs = 'CERT_REQUIRED' ,
54
+ ca_certs = certifi .where (),
55
+ socket_options = HTTPConnection .default_socket_options + [
56
+ (socket .SOL_SOCKET , socket .SO_KEEPALIVE , 1 ),
57
+ ])
58
+ proxy_url = _get_con_pool_proxy ()
59
+ if not proxy_url :
60
+ mgr = urllib3 .PoolManager
61
+ else :
62
+ kwargs ['proxy_url' ] = proxy_url
63
+ if _CON_POOL_PROXY_KWARGS :
64
+ kwargs .update (_CON_POOL_PROXY_KWARGS )
65
+ mgr = urllib3 .ProxyManager
66
+
67
+ _CON_POOL = mgr (** kwargs )
68
+
69
+
54
70
def is_con_pool_initialized ():
55
71
return _CON_POOL is not None
56
72
@@ -62,6 +78,47 @@ def stop_con_pool():
62
78
_CON_POOL = None
63
79
64
80
81
+ def set_con_pool_proxy (url , ** urllib3_kwargs ):
82
+ """Setup connection pool behind a proxy
83
+
84
+ Args:
85
+ url (str): The URL to the proxy server. For example: `http://127.0.0.1:3128`
86
+ urllib3_kwargs (dict): Arbitrary arguments passed as-is to `urllib3.ProxyManager`
87
+
88
+ """
89
+ global _CON_POOL_PROXY
90
+ global _CON_POOL_PROXY_KWARGS
91
+
92
+ if is_con_pool_initialized ():
93
+ raise TelegramError ('conpool already initialized' )
94
+
95
+ _CON_POOL_PROXY = url
96
+ _CON_POOL_PROXY_KWARGS = urllib3_kwargs
97
+
98
+
99
+ def _get_con_pool_proxy ():
100
+ """Return the user configured proxy according to the following order:
101
+
102
+ * proxy configured using `set_con_pool_proxy()`.
103
+ * proxy set in `HTTPS_PROXY` env. var.
104
+ * proxy set in `https_proxy` env. var.
105
+ * None (if no proxy is configured)
106
+
107
+ Returns:
108
+ str | None
109
+
110
+ """
111
+ if _CON_POOL_PROXY :
112
+ return _CON_POOL_PROXY
113
+ from_env = os .environ .get ('HTTPS_PROXY' )
114
+ if from_env :
115
+ return from_env
116
+ from_env = os .environ .get ('https_proxy' )
117
+ if from_env :
118
+ return from_env
119
+ return None
120
+
121
+
65
122
def _parse (json_data ):
66
123
"""Try and parse the JSON returned from Telegram.
67
124
0 commit comments