This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _send_request(self, path='/v1/getinfo') -> dict: | |
url = f'https://{self.hostname}:{self.port}{path}' | |
session = requests.Session() | |
try: | |
if self.tls_cert_verification: | |
adapter = CaDataVerifyingHTTPAdapter(tls_cert=self.tls_cert) | |
session.mount(url, adapter) | |
res = session.get(url, | |
headers={'Grpc-Metadata-macaroon': self.macaroon_readonly}, | |
timeout=3.0) | |
else: | |
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) | |
res = session.get(url, | |
headers={'Grpc-Metadata-macaroon': self.macaroon_readonly}, | |
verify=False, | |
timeout=3.0) | |
return {'data': res.json()} | |
except requests.exceptions.SSLError as err: | |
error = err.args[0] | |
print(error) | |
ssl_error = error.reason.args[0] | |
if hasattr(ssl, 'SSLCertVerificationError'): # introduced in Python3.7 | |
cert_err = isinstance(ssl_error, ssl.SSLCertVerificationError) | |
else: | |
cert_err = isinstance(ssl_error, ssl.CertificateError) | |
if cert_err: | |
if "[SSL: CERTIFICATE_VERIFY_FAILED]" in str(error.reason): | |
print(error.reason) | |
return {'error': error.reason} | |
elif "doesn't match either" in str(error.reason): | |
print(error.reason) | |
return {'error': error.reason} | |
print("Other SSL error") | |
print(error.reason) | |
return {'error': error.reason} | |
except requests.exceptions.ConnectionError as err: | |
error = err.args[0] | |
print("Other error") | |
print(error) | |
return {'error': error.reason} | |
class CaDataVerifyingHTTPAdapter(HTTPAdapter): | |
""" | |
A TransportAdapter ... | |
""" | |
def __init__(self, tls_cert, *args, **kwargs): | |
self.cadata = tls_cert | |
super().__init__(*args, **kwargs) | |
def init_poolmanager(self, *args, **kwargs): | |
context = ssl.create_default_context() | |
context.load_verify_locations(cadata=self.cadata) | |
if hasattr(ssl, 'HAS_NEVER_CHECK_COMMON_NAME'): # introduced in Python3.7 | |
context.hostname_checks_common_name = False | |
context.check_hostname = False | |
kwargs['ssl_context'] = context | |
return super().init_poolmanager(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment