diff options
Diffstat (limited to 'gn_libs')
-rw-r--r-- | gn_libs/debug.py | 16 | ||||
-rw-r--r-- | gn_libs/monadic_requests.py | 64 |
2 files changed, 75 insertions, 5 deletions
diff --git a/gn_libs/debug.py b/gn_libs/debug.py index 6b7173b..c1b896e 100644 --- a/gn_libs/debug.py +++ b/gn_libs/debug.py @@ -1,6 +1,6 @@ """Debug utilities""" import logging -from flask import current_app +import importlib.util __this_module_name__ = __name__ @@ -8,10 +8,16 @@ __this_module_name__ = __name__ # pylint: disable=invalid-name def getLogger(name: str): """Return a logger""" - return ( - logging.getLogger(name) - if not bool(current_app) - else current_app.logger) + flask_spec = importlib.util.find_spec("flask") + if bool(flask_spec): + current_app = importlib.import_module("flask").current_app + return ( + logging.getLogger(name) + if not bool(current_app) + else current_app.logger) + + return logging.getLogger(name) + def __pk__(*args): """Format log entry""" diff --git a/gn_libs/monadic_requests.py b/gn_libs/monadic_requests.py new file mode 100644 index 0000000..0a3c282 --- /dev/null +++ b/gn_libs/monadic_requests.py @@ -0,0 +1,64 @@ +"""Wrap requests functions with monads.""" +import logging + +import requests +from requests.models import Response +from pymonad.either import Left, Right, Either + +logger = logging.getLogger(__name__) + +# HTML Status codes indicating a successful request. +SUCCESS_CODES = (200, 201, 202, 203, 204, 205, 206, 207, 208, 226) + + +def get(url, params=None, **kwargs) -> Either: + """ + A wrapper around `requests.get` function. + + Takes the same arguments as `requests.get`. + + :rtype: pymonad.either.Either + """ + try: + resp = requests.get(url, params=params, **kwargs) + if resp.status_code in SUCCESS_CODES: + return Right(resp.json()) + return Left(resp) + except requests.exceptions.RequestException as exc: + return Left(exc) + + +def post(url, data=None, json=None, **kwargs) -> Either: + """ + A wrapper around `requests.post` function. + + Takes the same arguments as `requests.post`. + + :rtype: pymonad.either.Either + """ + try: + resp = requests.post(url, data=data, json=json, **kwargs) + if resp.status_code in SUCCESS_CODES: + return Right(resp.json()) + return Left(resp) + except requests.exceptions.RequestException as exc: + return Left(exc) + + +def make_either_error_handler(msg): + """Make generic error handler for pymonads Either objects.""" + def __fail__(error): + if issubclass(type(error), Exception): + logger.debug("\n\n%s (Exception)\n\n", msg, exc_info=True) + raise error + if issubclass(type(error), Response): + try: + _data = error.json() + except Exception as _exc: + raise Exception(error.content) from _exc + raise Exception(_data) + + logger.debug("\n\n%s\n\n", msg) + raise Exception(error) + + return __fail__ |