diff options
author | Frederick Muriuki Muriithi | 2024-07-26 16:43:49 -0500 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2024-07-26 16:45:29 -0500 |
commit | 46f12db2ef1250c9199d7720c5b9f1d5058d21e2 (patch) | |
tree | 0282fbaf0900a688561fe4aa39c3a19d78ab33ec /uploader/monadic_requests.py | |
parent | 30da248ba5281686c0045c21bdcd9355d449790a (diff) | |
download | gn-uploader-46f12db2ef1250c9199d7720c5b9f1d5058d21e2.tar.gz |
Add monadic wrapper for requests library.
Diffstat (limited to 'uploader/monadic_requests.py')
-rw-r--r-- | uploader/monadic_requests.py | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/uploader/monadic_requests.py b/uploader/monadic_requests.py new file mode 100644 index 0000000..d679fd3 --- /dev/null +++ b/uploader/monadic_requests.py @@ -0,0 +1,38 @@ +"""Wrap requests functions with monads.""" +import requests +from pymonad.either import Left, Right, Either + +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) |