Sebastian Goslin
Sebastian Goslin

Reputation: 497

Identifying and breaking on exception: 'OpenSSL.SSL.Error' using python's requests module

I'm currently parsing through a list of URLs and in the event that one throws an exception I want to just break and move on to the next one.

However, I keeping getting

OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

Solving this exception is beyond my expertise right now, so I want to just be able to skip it for now and handle that later. My problem, however, is when I write the try catch to do so:

    try:
        r = requests_retry_session(session=s).get(test_link, verify=cafile, allow_redirects=True, timeout=4.0)

    except OpenSSL.SSL.Error:
        print('SSL error, moving to next domain')
        break

I get this:

NameError: name 'OpenSSL' is not defined

I know the easiest way to fix this would be to just do verify=False, however, tthat'svery unsafe and I would rather not open myself up to a possible MITM attack.

What I've tried:

Attempting to follow the documentation of this previous related question:

pip install --upgrade certifi

And finally an extremely sloppy try catch block, that essentially catches NameError: name 'OpenSSL' is not defined and breaks on that as a name error, which is not pythonic at all. I know I can do a very general catch all, however, I don't want to skip all errors.

I'm running python 3.7.3 and requests 2.22.0

Upvotes: 3

Views: 1691

Answers (2)

Sebastian Goslin
Sebastian Goslin

Reputation: 497

Found the correct exception, its super trivial but confusing documentation.

So OpenSSL.SSL.Error would be caught by using requests.exceptions.SSLError, and importing OpenSSL or pyOpenSSL doesn't need to be done (explicitly) in this case.

Upvotes: 1

ipaleka
ipaleka

Reputation: 3957

Attempting to follow the documentation of this previous related question

You should have solved this exception handling by following those instructions and having pyopenssl (pip install pyopenssl) installed and its OpenSSL imported at the top of your module.

Upvotes: 1

Related Questions