解決python2.x用urllib2證書驗證錯誤, _create_unverified_context


解決以下錯誤:

錯誤1:AttributeError: 'module' object has no attribute '_create_unverified_context',

錯誤2:URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)>

 

在代碼中加入以下代碼:

復制代碼
 1 import ssl
 2 
 3 try:
 4     _create_unverified_https_context = ssl._create_unverified_context
 5 except AttributeError:
 6     # Legacy Python that doesn't verify HTTPS certificates by default
 7     pass
 8 else:
 9     # Handle target environment that doesn't support HTTPS verification
10     ssl._create_default_https_context = _create_unverified_https_context
復制代碼

官方解釋:

復制代碼
This guidance is aimed primarily at system administrators that wish to adopt newer 
versions of Python that implement this PEP in legacy environments that do not yet
support certificate verification on HTTPS connections. For example, an administrator
may opt out by adding the monkeypatch above to sitecustomize.py in their Standard
Operating Environment for Python. Applications and libraries SHOULD NOT be making
this change process wide (except perhaps in response to a system administrator
controlled configuration setting). Particularly security sensitive applications should always provide an explicit
application defined SSL context rather than relying on the default behaviour
of the underlying Python implementation.
復制代碼

 

Python訪問https鏈接錯誤排查

 

1. 遇到這種錯誤有可能是機器無外網權限造成的。

  requests.exceptions.ConnectionError: HTTPSConnectionPool(host='', port=443): Max retries exceeded with url: /s/savecomtajax (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f972f48bf90>: Failed to establish a new connection: [Errno 110] Connection timed out',))

2.  requests 發https 請求時,需要忽略證書的驗證, 需要注意如下點。

requests.packages.urllib3.disable_warnings()
def request_ajax_url(login_url,login_body, headers):
    '''發送post請求數據'''
    req = requests.post(login_url, data=login_body, headers=headers, verify=False);
    return  req.text

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM