import warnings
import contextlib
import requests
from urllib3.exceptions import InsecureRequestWarning
old_merge_environment_settings = requests.Session.merge_environment_settings
@contextlib.contextmanager
def no_ssl_verification():
opened_adapters = set()
def merge_environment_settings(self, url, proxies, stream, verify, cert):
# Verification happens only once per connection so we need to close
# all the opened adapters once we're done. Otherwise, the effects of
# verify=False persist beyond the end of this context manager.
opened_adapters.add(self.get_adapter(url))
settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
settings['verify'] = False
return settings
requests.Session.merge_environment_settings = merge_environment_settings
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', InsecureRequestWarning)
yield
finally:
requests.Session.merge_environment_settings = old_merge_environment_settings
for adapter in opened_adapters:
try:
adapter.close()
except:
pass
以下是使用方法:
with no_ssl_verification():
requests.get('https://wrong.host.badssl.com/')
print('It works')
requests.get('https://wrong.host.badssl.com/', verify=True)
print('Even if you try to force it to')
requests.get('https://wrong.host.badssl.com/', verify=False)
print('It resets back')
session = requests.Session()
session.verify = True
with no_ssl_verification():
session.get('https://wrong.host.badssl.com/', verify=True)
print('Works even here')
try:
requests.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks')
try:
session.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
print('It breaks here again')
import requests
from urllib3.exceptions import InsecureRequestWarning
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)
要添加到Blender's answer,可以使用
Session.verify = False
对所有请求禁用SSL请注意,
urllib3
(哪个请求使用),strongly discourages生成未验证的HTTPS请求,并将引发一个InsecureRequestWarning
。来自the documentation:
如果您正在使用第三方模块并希望禁用检查,这里有一个上下文管理器,它可以对
requests
进行修补并对其进行更改,使verify=False
成为默认值并抑制警告。以下是使用方法:
请注意,一旦您离开上下文管理器,此代码将关闭处理修补请求的所有打开的适配器。这是因为请求维护每个会话连接池,而证书验证在每个连接中只发生一次,因此会发生以下意外情况:
对
requests
方法使用requests.packages.urllib3.disable_warnings()
和verify=False
。相关问题 更多 >
编程相关推荐