Python屏蔽InsecureRequestWarning报错

使用Python3 requests发送HTTPS请求,在关闭SSL认证(verify=False)的情况下:

import requests
response = requests.get(url='http://127.0.0.1:12345/test', verify=False)

会出现如下错误:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

解决:

#python3
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#python2
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

PS:如下所示,disable_warnings()代表屏蔽全部warning类型。

def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter("ignore", category)