def __init__(self): self.__pool = HTTPSConnectionPool(host=NetMod.__api_base, maxsize=NetMod.__pool_size, headers=NetMod.__headers, timeout=NetMod.__timeout, port=NetMod.__port, block=True)
def test_same_host_no_port(self): # This test was introduced in #801 to deal with the fact that urllib3 # never initializes ConnectionPool objects with port=None. same_host_http = [ ('google.com', '/'), ('google.com', 'http://google.com/'), ('google.com', 'http://google.com'), ('google.com', 'http://google.com/abra/cadabra'), # Test comparison using default ports ('google.com', 'http://google.com:80/abracadabra'), ] same_host_https = [ ('google.com', '/'), ('google.com', 'https://google.com/'), ('google.com', 'https://google.com'), ('google.com', 'https://google.com/abra/cadabra'), # Test comparison using default ports ('google.com', 'https://google.com:443/abracadabra'), ] for a, b in same_host_http: c = HTTPConnectionPool(a) self.addCleanup(c.close) self.assertTrue(c.is_same_host(b), "%s =? %s" % (a, b)) for a, b in same_host_https: c = HTTPSConnectionPool(a) self.addCleanup(c.close) self.assertTrue(c.is_same_host(b), "%s =? %s" % (a, b)) not_same_host_http = [ ('google.com', 'https://google.com/'), ('yahoo.com', 'http://google.com/'), ('google.com', 'https://google.net/'), ] not_same_host_https = [ ('google.com', 'http://google.com/'), ('yahoo.com', 'https://google.com/'), ('google.com', 'https://google.net/'), ] for a, b in not_same_host_http: c = HTTPConnectionPool(a) self.addCleanup(c.close) self.assertFalse(c.is_same_host(b), "%s =? %s" % (a, b)) c = HTTPConnectionPool(b) self.addCleanup(c.close) self.assertFalse(c.is_same_host(a), "%s =? %s" % (b, a)) for a, b in not_same_host_https: c = HTTPSConnectionPool(a) self.addCleanup(c.close) self.assertFalse(c.is_same_host(b), "%s =? %s" % (a, b)) c = HTTPSConnectionPool(b) self.addCleanup(c.close) self.assertFalse(c.is_same_host(a), "%s =? %s" % (b, a))
def __init__(self, host, port, certfile=None, keyfile=None, cacertfile=None, force_ssl=False, *args, **kw): super(ConnectionPoolManager, self).__init__(*args, **kw) self.logger.debug("Creating ConnectionPoolManager for %s:%s", host, port) if certfile or keyfile or force_ssl: #https://docs.python.org/2/library/ssl.html#ssl.SSLContext from ssl import SSLContext, PROTOCOL_SSLv23 ssl_context = SSLContext(PROTOCOL_SSLv23) ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile) ssl_context.load_verify_locations(cafile=cacertfile) #https://docs.python.org/2/library/httplib.html self.__pool = HTTPSConnectionPool(host, port, maxsize=16, context=ssl_context) else: self.__pool = HTTPConnectionPool(host, port, maxsize=16)
def connect(self): self.ca_cert_path = os.path.join(self.working_dir, "ca.crt") self.cert_path = os.path.join(self.working_dir, "web.crt") self.key_path = os.path.join(self.working_dir, "web.key") uuid = None # do we have a ca certificate, key and cert? if os.path.exists(self.ca_cert_path) == False or \ os.path.exists(self.cert_path) == False or \ os.path.exists(self.key_path) == False: # request it from the server # don't validate the server certificate as we don't have the ca yet # this is obviously opportunistic encryption urllib3.disable_warnings() self.pool = HTTPSConnectionPool(self.server_host, \ port=self.server_port, cert_reqs="CERT_NONE", \ assert_hostname=False, timeout=self.HTTP_POOL_TIMEOUT, \ maxsize=self.MAX_DAEMON_CONNECTIONS) self.request_cert() self.start_pool() json_result = self.register() uuid = json_result["uuid"] else: self.start_pool() self.get_server_info()
def create_profile_single_use_token_2(self): data = { "card": { "holderName": "MR. JOHN SMITH", "cardNum": "4917484589897107", "cardExpiry": { "month": "12", "year": "2019" }, "billingAddress": { "street": "100 Queen Street West", "street2": "Unit 201", "city": "Toronto", "country": "CA", "state": "ON", "zip": "M5H 2N2" } } } #username = '******' #password = '******' url = "/customervault/v1/singleusetokens" header_content = {"content-type": "application/json;charset=utf-8"} header_auth = {"Authorization": "Basic T1QtMTYxNTY6Qi1xYTItMC01NTJiOWJjZi0wLTMwMmMwMjE0NGVkOGY5YjhhZWE5ZDY1YjQ0Yjc3YTE2YTgxZWM1ZjlhYjkxNmY4YzAyMTQyYjRlNjliM2EyNzJiODY2YjFlMjYzYjBiMGM3YTkyNWE4OTQ1NDE4"} #auth_header = urllib3.util.make_headers(basic_auth=username+":"+password) pool = HTTPSConnectionPool('api.test.netbanx.com', cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) pool.headers.update(header_content) pool.headers.update(header_auth) response = pool.urlopen("POST", url, body=json.dumps(data)) print (response.status) print (response.data) res = response.data resp_str = res.decode('utf-8') json_obj = json.loads(resp_str) print ("payment token", json_obj['paymentToken']) return (json_obj['paymentToken'])
def __init__(self, host_url, max_connections, pool_enable, connection_timeout, read_timeout): ''' Constructor ''' if connection_timeout is None: connection_timeout = 30 if read_timeout is None: read_timeout = 30 self._host_url = host_url self._pool = HTTPSConnectionPool(host_url, maxsize=max_connections, block=pool_enable, timeout=Timeout( connect=connection_timeout, read=read_timeout), retries=False, cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
def test_not_same_host_no_port_https(self, a, b): with HTTPSConnectionPool(a) as c: assert not c.is_same_host(b) with HTTPSConnectionPool(b) as c: assert not c.is_same_host(a)
def test_same_host_no_port_https(self, a, b): # This test was introduced in #801 to deal with the fact that urllib3 # never initializes ConnectionPool objects with port=None. with HTTPSConnectionPool(a) as c: assert c.is_same_host(b)
class NetMod: _instance = None __pool: HTTPSConnectionPool __pool_size: int = 5 __api_base: str = 'api.github.com' __port: int = 443 __timeout: float = 5.0 __repo_route: Template = Template('/repos/$repo') __user_route: Template = Template('/users/$user') __org_route: Template = Template('/users/$user/orgs') """ explicitly request v3 of the API https://docs.github.com/en/rest/overview/resources-in-the-rest-api#current-version """ __headers: Dict[str, str] = { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'Python-urllib/3', 'Authorization': '' } """ referenced from https://python-patterns.guide/gang-of-four/singleton/ """ def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(NetMod, cls).__new__(cls) return cls._instance def __init__(self): self.__pool = HTTPSConnectionPool(host=NetMod.__api_base, maxsize=NetMod.__pool_size, headers=NetMod.__headers, timeout=NetMod.__timeout, port=NetMod.__port, block=True) def __make_request(self, api_route: str, method: str = 'get') -> Dict[str, Any]: try: response: HTTPResponse = self.__pool.request(method, api_route, release_conn=True, redirect=True) res_data = json.loads(response.data) if response.status != 200: raise HTTPError(response.status, res_data['message']) return res_data except (NewConnectionError, MaxRetryError): sys.exit("""Failed to connect. Exiting...""") except HTTPError as err: sys.exit(err) def fetch_repos_data(self, repos: List[str]) -> Dict[str, Any]: api_routes = [ self.__repo_route.substitute(repo=repo) for repo in repos ] return self.__fetch_all__concurrent(repos, api_routes) def fetch_users_data(self, users: List[str]) -> Dict[str, Any]: api_routes = [ self.__user_route.substitute(user=user) for user in users ] return self.__fetch_all__concurrent(users, api_routes) def fetch_org_data(self, user: str) -> Dict[str, Any]: api_route = self.__org_route.substitute(user=user) return self.__make_request(api_route) def __fetch_all__concurrent(self, entries: List[str], api_routes: List[str]) -> Dict[str, Any]: max_workers = max(len(entries), self.__pool_size) with ThreadPoolExecutor(max_workers=max_workers) as executor: res: Dict[str, Future[Dict[str, Any]]] = { entry: executor.submit(self.__make_request, route) for entry, route in zip(entries, api_routes) } return {user: data.result() for user, data in res.items()}
def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1, block=False, headers=headers, key_file=None, cert_file=None, cert_reqs="CERT_NONE", ca_certs=None): RegularOpener.__init__(self, host, port, strict, timeout, maxsize, block, headers) HTTPSConnectionPool.__init__(self, host, port, strict, timeout, maxsize, block, headers, key_file, cert_file, cert_reqs, ca_certs)
def start_pool(self): self.pool = HTTPSConnectionPool(self.server_host, \ port=self.server_port, cert_reqs="CERT_REQUIRED", \ key_file=self.key_path, cert_file=self.cert_path, \ ca_certs=self.ca_cert_path, assert_hostname=False)