gpt4 book ai didi

python-requests - 如何使用请求库和 Python 3.8.5 禁用 "check_hostname"?

转载 作者:行者123 更新时间:2023-12-04 13:33:01 25 4
gpt4 key购买 nike

使用最新的请求库和 Python 3.8.5,我似乎无法“禁用”对 API 调用的证书检查。我了解不禁用的原因,但我希望它起作用。
当我尝试使用“verify=True”时,我连接的服务器抛出此错误:

(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')))
当我尝试使用“verify=False”时,我得到:
Error making PS request to [<redacted server name>] at URL https://<redacted server name/rest/v2/api_endpoint: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.
我不知道如何也禁用“check_hostname”,因为我还没有看到使用请求库(我计划保留和使用)来做到这一点的方法。
我的代码:
self.ps_server = server
self.ps_base_url = 'https://{}/rest/v2/'.format(self.ps_server)
url = self.ps_base_url + endpoint

response = None
try:
if req_type == 'POST':
response = requests.post(url, json=post_data, auth=(self.ps_username, self.ps_password), verify=self.verify, timeout=60)
return json.loads(response.text)
elif req_type == 'GET':
response = requests.get(url, auth=(self.ps_username, self.ps_password), verify=self.verify, timeout=60)
if response.status_code == 200:
return json.loads(response.text)
else:
logging.error("Error making PS request to [{}] at URL {} [{}]".format(server, url, response.status_code))
return {'status': 'error', 'trace': '{} - {}'.format(response.text, response.status_code)}
elif req_type == 'DELETE':
response = requests.delete(url, auth=(self.ps_username, self.ps_password), verify=self.verify, timeout=60)
return response.text
elif req_type == 'PUT':
response = requests.put(url, json=post_data, auth=(self.ps_username, self.ps_password), verify=self.verify, timeout=60)
return response.text
except Exception as e:
logging.error("Error making PS request to [{}] at URL {}: {}".format(server, url, e))
return {'status': 'error', 'trace': '{}'.format(e)}
有人可以解释一下我如何禁用 check_hostname ,以便我可以在没有 SSL 检查的情况下进行测试吗?

最佳答案

如果您有 pip-system-certs ,它猴子补丁requests以及。这是代码的链接:https://gitlab.com/alelec/pip-system-certs/-/blob/master/pip_system_certs/wrapt_requests.py
经过挖掘requestsurllib3来源一段时间,这是pip-system-certs的罪魁祸首:

ssl_context = ssl.create_default_context()
ssl_context.load_default_certs()
kwargs['ssl_context'] = ssl_context
该 dict 用于获取 ssl_context后来来自 urllib3连接池但它有 .check_hostname设置为 True在上面。
至于替换 pip-system-certs的实用程序包,我认为将它 fork 并使其成为唯一的猴子补丁 pip 将是正确的前进方向。那或只是添加 --trusted-host args 到任何 pip install命令。
编辑:
这是它通常通过请求(我正在使用的版本)初始化的方式:
https://github.com/psf/requests/blob/v2.21.0/requests/adapters.py#L163
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block

# NOTE: pool_kwargs doesn't have ssl_context in it
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
这是猴子修补的方式:
def init_poolmanager(self, *args, **kwargs):
import ssl
ssl_context = ssl.create_default_context()
ssl_context.load_default_certs()
kwargs['ssl_context'] = ssl_context
return super(SslContextHttpAdapter, self).init_poolmanager(*args, **kwargs)

关于python-requests - 如何使用请求库和 Python 3.8.5 禁用 "check_hostname"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63890259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com