How to fix Python SSL CERTIFICATE_VERIFY_FAILED

By | September 2, 2017

Here I explain how to fix Python SSL errors when downloading web pages using the https protocol in Python (e.g. by using the urllib, urllib2, httplib or requests. This error looks like (possibly with a line number different from 509):

self._sslobj.do_handshake()
 SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

Server certificate verification by default has been introduced to Python recently (in 2.7.9). This protects against man-in-the-middle attacks, and it makes the client sure that the server is indeed who it claims to be.

As a quick (and insecure) fix, you can turn certificate verification off, by:

  1. Set PYTHONHTTPSVERIFY environment variable to 0. For example, run
export PYTHONHTTPSVERIFY=0
python your_script

or

PYTHONHTTPSVERIFY=0 python your_script
  1. Alternatively, you can add this to your code before doing the https request
import os, ssl
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and 
    getattr(ssl, '_create_unverified_context', None)): 
    ssl._create_default_https_context = ssl._create_unverified_context

Leave a Reply

Your email address will not be published. Required fields are marked *