about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2025-01-21 16:09:55 -0600
committerFrederick Muriuki Muriithi2025-01-21 16:10:08 -0600
commit72a95f8ffa5401649f70978e863dd3f21900a611 (patch)
treeb66c6044a53daee32795cc52c324965d967c6ce0
parent761ee64e832dcd38dc1b6d0701b48ee468fb7113 (diff)
downloadgn-libs-72a95f8ffa5401649f70978e863dd3f21900a611.tar.gz
Add monadic_requests module. genenetwork-system-v1.0.0
-rw-r--r--gn_libs/monadic_requests.py64
-rw-r--r--mypy.ini3
2 files changed, 67 insertions, 0 deletions
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__
diff --git a/mypy.ini b/mypy.ini
index 2373597..ca04070 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -8,4 +8,7 @@ ignore_missing_imports = True
 ignore_missing_imports = True
 
 [mypy-pymonad.*]
+ignore_missing_imports = True
+
+[mypy-requests.*]
 ignore_missing_imports = True
\ No newline at end of file