-1

I am using python-requests and noticed that it returns unrelated errors after failing to fetch a web page when not connected to the Internet.

The documentation mentions Exceptions, but not how to use them. How should the program verify that it is indeed connected, and fail nicely if not?

I currently have no error-handling system in place, and this is what I get:

File "mem.py", line 78, in <module>
    login()
  File "mem.py", line 38, in login
    csrf = s.cookies['csrftoken']
  File "/usr/local/lib/python2.7/site-packages/requests/cookies.py", line 276, in __getitem__
    return self._find_no_duplicates(name)
  File "/usr/local/lib/python2.7/site-packages/requests/cookies.py", line 331, in _find_no_duplicates
    raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"
octosquidopus
  • 3,517
  • 8
  • 35
  • 53

1 Answers1

2

It appears that HTTP errors are not raised by default in python-requests. This answer sums it up nicely: https://stackoverflow.com/a/24460981/908703

import requests

def connected_to_internet(url='http://www.google.com/', timeout=5):
    try:
        _ = requests.get(url, timeout=timeout)
        return True
    except requests.ConnectionError:
        print("No internet connection available.")
    return False
Community
  • 1
  • 1
octosquidopus
  • 3,517
  • 8
  • 35
  • 53