-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrest.py
76 lines (61 loc) · 1.98 KB
/
rest.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
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
import traceback
from flask import jsonify, make_response, send_from_directory
from flask_restx import fields, Resource
from json import JSONEncoder
from datetime import date, datetime
from context import swagger
from log import logger
##################################################
# REST API related definitions
##################################################
class ISerializable:
'''serializable interface
'''
pass
class AppJSONEncoder(JSONEncoder):
'''json encoder for serialization
'''
def default(self, obj):
if isinstance(obj, (ISerializable)):
return obj.__dict__
if isinstance(obj, (date, datetime)):
return obj.__str__()
if isinstance(obj, bytes):
return obj
return JSONEncoder.default(self, obj)
def request_handle(func):
'''
decorator for generic error handling
'''
def handle(*args, **kwargs):
try:
resp = func(*args, **kwargs)
except Exception as e:
resp = Response(500, 'Internal Server Error', {})
error_detail = traceback.format_exc()
logger.error('\n' + error_detail)
resp.data['error_detail'] = str(e)
# resp.data['error_detail'] = error_detail.strip().split('\n')
finally:
return make_response(jsonify(resp), resp.code)
handle.__name__ = func.__name__
return handle
class Response(ISerializable):
'''base response class
'''
def __init__(self, code=200, msg='success', data=None):
self.code = code
self.msg = msg
self.data = data
# base response api docs
response_model = swagger.model('Response', {
'code': fields.Integer(description='response code'),
'msg': fields.String(description='response message'),
'data': fields.Raw
})
@swagger.response(200, 'ok', model=response_model)
# @swagger.response(500, 'error', model=response_model)
class BaseResource(Resource):
'''base rest api router class
'''
pass