errorhandler.py 3.36 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- encoding: utf-8 -*-
# -----------------------------------------------------------------------------
# @File Name  : errorhandler.py
# @Time       : 2020/11/25 上午9:19
# @Author     : X. Peng
# @Email      : acepengxiong@163.com
# @Software   : PyCharm
# -----------------------------------------------------------------------------
9 10
import time

11
import requests
12
from flask import jsonify, make_response, request
13

pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
14
from app.api.engine import config, env, redis
15
from app.config.errors import Errors
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
16
from app.api.engine import logging
17 18 19 20 21 22 23 24 25 26 27 28 29 30


class CustomFlaskErr(Exception):
    # 默认的返回码
    status_code = 200

    # 自己定义了一个 return_code,作为更细颗粒度的错误代码
    def __init__(self, return_code=None, status_code=None, payload=None):
        Exception.__init__(self)
        self.return_code = return_code
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
31

32 33 34 35 36
    # 构造要返回的错误代码和错误信息的 dict
    def to_dict(self):
        rv = dict(self.payload or ())

        # 增加 dict key: return code
37
        rv['statusCode'] = self.return_code
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

        # 增加 dict key: message, 具体内容由常量定义文件中通过 return_code 转化而来
        rv['message'] = Errors.MSG[self.return_code]

        return rv
def add_errorhandler(app):
    @app.errorhandler(CustomFlaskErr)
    def handle_flask_error(error):
        # response 的 json 内容为自定义错误代码和错误信息
        response = jsonify(error.to_dict())

        # response 返回 error 发生时定义的标准错误代码
        response.status_code = error.status_code

        return response
53

54 55 56 57 58 59 60 61 62 63
    @app.errorhandler(500)
    def handle_flask_error(error):
        # response 的 json 内容为自定义错误代码和错误信息
        response = jsonify({'statusCode': '9999', 'message': '服务器错误'})

        # response 返回 error 发生时定义的标准错误代码
        response.status_code = 200

        return response

64 65 66

    @app.before_request
    def before_request():
67
        # token鉴权
68 69 70 71 72
        # 安卓,ios取token
        token = ''
        if request.headers.get('env') in ['ios', 'android']:
            token = request.headers.get('tampToken', '')
        elif request.headers.get('env') in ['wechat', 'xcx']:
pengxiong's avatar
pengxiong committed
73
            token = request.cookies.get('qimsession', '')
74 75 76
        if request.path in ['/tamp_order/micro_shop/topUpOrderNotify', '/tamp_order/micro_shop/consumeOrderNotify']:
            pass
        else:
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
77
            user_id = redis.get('s:sid:'+token)
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
78
            if not user_id:
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
79
                logging.error('鉴权失败,token:'+token)
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
80
                raise CustomFlaskErr(Errors.TOKEN_INVALID)
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
81
            if isinstance(user_id, bytes):
82
                request.user_id = user_id.decode().replace('"', '')
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
83 84
            else:
                request.user_id = user_id.replace('"', '')
85
        request.return_success = {'statusCode': "0000", 'message': 'ok'}
86 87 88

    @app.after_request
    def after_request(response):
pengxiong's avatar
pengxiong committed
89 90 91 92 93 94
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE,OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = (
                "Content-Type,Referer,Accept,Origin,User-Agent"
                "field,Cache-Control,X-Requested-With"
            )
95
        return response