1919"""This module contains methods to make POST and GET requests"""
2020
2121import json
22+ import os
2223import socket
2324import logging
2425
3132
3233_CON_POOL = None
3334""":type: urllib3.PoolManager"""
35+ _CON_POOL_PROXY = None
36+ _CON_POOL_PROXY_KWARGS = {}
3437CON_POOL_SIZE = 1
3538
3639logging .getLogger ('urllib3' ).setLevel (logging .WARNING )
3740
3841
3942def _get_con_pool ():
40- global _CON_POOL
41-
4243 if _CON_POOL is not None :
4344 return _CON_POOL
4445
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 ()
5147 return _CON_POOL
5248
5349
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+
5470def is_con_pool_initialized ():
5571 return _CON_POOL is not None
5672
@@ -62,6 +78,47 @@ def stop_con_pool():
6278 _CON_POOL = None
6379
6480
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+
65122def _parse (json_data ):
66123 """Try and parse the JSON returned from Telegram.
67124
0 commit comments