diff options
author | MS <ms@taler.net> | 2020-07-22 17:08:18 +0200 |
---|---|---|
committer | MS <ms@taler.net> | 2020-07-22 17:14:54 +0200 |
commit | 4c364161fabffb95bdf5443037cf67f5ec208aa1 (patch) | |
tree | a5544dbe75cbd4952a30703e201c067053c7d6a6 /talermerchantdemos/httpcommon | |
parent | 14fb4a58c6c585d23f353c491d45b31bf3a4ab14 (diff) | |
download | taler-merchant-demos-4c364161fabffb95bdf5443037cf67f5ec208aa1.tar.gz taler-merchant-demos-4c364161fabffb95bdf5443037cf67f5ec208aa1.tar.bz2 taler-merchant-demos-4c364161fabffb95bdf5443037cf67f5ec208aa1.zip |
factor out http code
Diffstat (limited to 'talermerchantdemos/httpcommon')
-rw-r--r-- | talermerchantdemos/httpcommon/__init__.py | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/talermerchantdemos/httpcommon/__init__.py b/talermerchantdemos/httpcommon/__init__.py new file mode 100644 index 0000000..1aecbcd --- /dev/null +++ b/talermerchantdemos/httpcommon/__init__.py @@ -0,0 +1,63 @@ +import requests + +## +# POST a request to the backend, and return a error +# response if any error occurs. +# +# @param endpoint the backend endpoint where to POST +# this request. +# @param json the POST's body. +# @return the backend response (JSON format). +def backend_post(backend_url, endpoint, json): + headers = {"Authorization": "ApiKey " + APIKEY} + try: + resp = requests.post( + urljoin(backend_url, endpoint), json=json, headers=headers + ) + except requests.ConnectionError: + err_abort(500, message="Could not establish connection to backend") + try: + response_json = resp.json() + except ValueError: + err_abort( + 500, + message="Could not parse response from backend", + status_code=resp.status_code + ) + if resp.status_code != 200: + err_abort( + 500, + message="Backend returned error status", + json=response_json, + status_code=resp.status_code + ) + return response_json + + +## +# Issue a GET request to the backend. +# +# @param endpoint the backend endpoint where to issue the request. +# @param params (dict type of) URL parameters to append to the request. +# @return the JSON response from the backend, or a error response +# if something unexpected happens. +def backend_get(backend_url, endpoint, params): + headers = {"Authorization": "ApiKey " + APIKEY} + try: + resp = requests.get( + urljoin(backend_url, endpoint), params=params, headers=headers + ) + except requests.ConnectionError: + err_abort(500, message="Could not establish connection to backend") + try: + response_json = resp.json() + except ValueError: + err_abort(500, message="Could not parse response from backend") + if resp.status_code != 200: + err_abort( + 500, + message="Backend returned error status", + json=response_json, + status_code=resp.status_code + ) + return response_json |