Flask封装响应包

主要记录Flask封装响应包,包括返回json内容、状态码、Header、Cookie信息。

通过Flask的Response封装响应包

1
# -*- coding: UTF-8 -*-
2
__author__ = 'Joynice'
3
from flask import Response
4
from enum import Enum, unique
5
import json
6
7
@unique
8
class ResponseCodeEnum(Enum):
9
    GET_SUCCESS = '200'
10
    POST_SUCCESS = '201'
11
    BAD_REQUEST = '400'
12
    UNAUTHORIZED = '401'
13
    FORBIDDEND = '403'
14
    NOT_FOUND = '404'
15
    METHOD_NOT_ALLOWED = '405'
16
17
    @classmethod
18
    def code(cls):
19
        return [cls.GET_SUCCESS.value, cls.POST_SUCCESS.value, cls.BAD_REQUEST.value, cls.UNAUTHORIZED.value,
20
                cls.FORBIDDEND.value, cls.NOT_FOUND.value, cls.METHOD_NOT_ALLOWED.value]
21
22
23
class MyResponse():
24
25
    def __set_cookie(self, resp, cookie):
26
        if isinstance(cookie, dict):
27
            for key, value in cookie:
28
                resp.set_cookie(key, value)
29
            return resp
30
        else:
31
            raise TypeError('cookie must dict')
32
33
    def __set_header(self, resp, header):
34
        if isinstance(header, dict):
35
            for key, value in header:
36
                resp.headers[key] = value
37
            return resp
38
        else:
39
            raise TypeError('header must dict')
40
41
    def restful_result(self, message, data, success):
42
        return {"message": message, "data": data or {}, "success": success or ''}
43
44
    def get_response(self, status, data=None, message=None, success=None, cookie=None, header=None):
45
        '''
46
        封装相应包, 相应类型json
47
        :param status: 状态码
48
        :param data:
49
        :param message:
50
        :param success:
51
        :param cookie:
52
        :param header:
53
        :return:
54
        '''
55
        resp = Response(json.dumps(self.restful_result(message=message, data=data, success=success)),
56
                        content_type='application/json')
57
        if status not in ResponseCodeEnum.code():
58
            raise Exception('状态码不可用')
59
        resp.status = status
60
        if cookie:
61
            resp = self.__set_cookie(resp, cookie)
62
        if header:
63
            resp = self.__set_header(resp, header)
64
        return resp
65
66
myresponse = MyResponse()