1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
import flask
import requests
from urllib.parse import urljoin
##
# Return a error response to the client.
#
# @param abort_status_code status code to return along the response.
# @param params _kw_ arguments to passed verbatim to the templating engine.
def err_abort(abort_status_code, **params):
t = flask.render_template("templates/error.html", **params)
flask.abort(flask.make_response(t, abort_status_code))
##
# 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 sandbox"}
final_url = urljoin(backend_url, endpoint)
print("POSTing to: " + final_url)
try:
resp = requests.post(
final_url, 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 sandbox"}
final_url = urljoin(backend_url, endpoint)
print("GETting: " + final_url)
try:
resp = requests.get(
final_url, 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
|