-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_utils.py
49 lines (39 loc) · 1.28 KB
/
web_utils.py
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
"""Collection of HTTP helpers."""
from functools import partial, wraps
from inspect import iscoroutine
from aiohttp.web import (
json_response, HTTPError,
HTTPSuccessful, HTTPRedirection
)
def async_json_out(orig_method=None, *, status=200, content_type='application/json', **dec_kwargs):
"""Turn dict output of an HTTP handler into JSON response.
Decorates aiohttp request handlers.
"""
if orig_method is None:
return partial(async_json_out, status=200, content_type='application/json', **dec_kwargs)
@wraps(orig_method)
async def wrapper(*args, **kwargs):
try:
dict_resp = orig_method(*args, **kwargs)
if iscoroutine(dict_resp):
dict_resp = await dict_resp
except (HTTPSuccessful, HTTPRedirection):
raise
except HTTPError as he:
if he.empty_body:
raise
status = he.status_code,
dict_resp = {
'error': he.body,
}
try:
status = dict_resp['status']
except KeyError:
dict_resp['status'] = status
return json_response(
dict_resp,
status=status,
content_type=content_type,
**dec_kwargs
)
return wrapper