bpeterso2000
12/5/2015 - 8:26 PM

Example of general use case error handling for the requests module in Python 3.x

Example of general use case error handling for the requests module in Python 3.x

import json
import sys

import requests

def exit_with_error(e):
  sys.stderr.write(str(e))
  sys.exit(1)


def request(url, **kwds):
    try:
        repsonse = requests.get(url, **kwds)
    except RequestException as e:
        exit_with_error(e)
  
    if response.status_code == 200:
        try:
          return response.json()
        except ValueError as e:
          exit_with_error(e)

    sys.stderr.write(str(e))
    try:
        sys.stderr.write(json.dumps(response.json(), indent=2))
    except (TypeError, json.JSONDecodeError):
        pass
import json
import sys

import requests


def request(url, auth=None, headers=None, params=None, data=None, method='get'):
    try:
        if data is not None:
          repsonse = requests.get(url, auth=auth, headers=headers, params=params)
        kwds = dict(auth=auth, headers=headers, params=params, data=data)
        response = getattr(requests, method)(url, **kwds)
        if response.status_code == 200:
            return response.json()
        print(json.dumps(response.json(), indent=2), file=sys.stderr)
        response.raise_for_status()
    except (RequestException, HTTPError, TypeError, ValueError,
            json.JSONDecodeError) as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)