response.py
1.62 KB
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
import enum
from django.http import JsonResponse, HttpResponse
from .named_enum import NamedEnum
def res_content(meta_status, msg, data=None):
res = {'code': meta_status, 'message': msg}
if data is not None:
res['data'] = data
return res
@enum.unique
class MetaStatus(NamedEnum):
SUCCESS = (0, 'success')
NEED_LOGIN = (1, 'need login')
INVALID_PARAMS = (2, 'invalid params')
INTERNAL_ERROR = (3, 'internal error')
NOT_EXIST = (4, 'object not exist')
ASYNC_WAIT = (5, 'async wait')
NO_PERMISSION = (6, 'no permission')
ILLEGAL_OPERATION = (7, 'illegal operation')
NEED_UPDATE = (8, 'need update')
class APIResponse(JsonResponse):
def __init__(self, meta_status, data=None, msg='', json_dumps_params=None, **kwargs):
data = res_content(meta_status, msg, data)
json_dumps_params = json_dumps_params or {'ensure_ascii': False}
kwargs['json_dumps_params'] = json_dumps_params
super().__init__(data, **kwargs)
def ok(**kwargs):
return APIResponse(MetaStatus.SUCCESS.value, msg=MetaStatus.SUCCESS.verbose_name, **kwargs)
def error_msg(msg='internal error', **kwargs):
return APIResponse(MetaStatus.INTERNAL_ERROR.value, msg=msg, **kwargs)
def need_update(**kwargs):
return APIResponse(MetaStatus.NEED_UPDATE.value, msg=MetaStatus.NEED_UPDATE.verbose_name, **kwargs)
def excel_response(file_name, io_content):
http_response = HttpResponse(content_type="application/vnd.ms-excel")
http_response['Content-Disposition'] = 'attachment;filename={0}.xlsx'.format(file_name)
http_response.write(io_content.getvalue())
return http_response