-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_lib.py
47 lines (36 loc) · 1.04 KB
/
json_lib.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
import logging
import inspect
import json
import sys
import config
from flask import request
def error(message):
return json.dumps({'error': message})
def ok():
return json.dumps({'message': 'OK'})
def json_request(func, methods = []):
def wrapper(**kwargs):
try:
# Check request data
if request.method == 'POST':
if len(request.data) > config.MAX_JSON_DATA_SIZE:
raise ValueError("POSTed too much data")
# Read request data
data = json.loads(request.data)
else:
data = {}
# Populate arguments for wrapped function
wrapped_kwargs = dict()
for arg in inspect.getargspec(func)[0]:
if arg in kwargs:
wrapped_kwargs[arg] = kwargs[arg]
else:
wrapped_kwargs[arg] = data[arg]
# Call wrapped function
return func(**wrapped_kwargs)
except Exception as e:
logging.exception(e)
return error("Internal error")
wrapped_function = wrapper
wrapped_function.__name__ = func.__name__
return wrapped_function