Flask restful实现(二)

2018-06-21  本文已影响107人  andpy

Flask resetful 配置

当Falsk遇到异常的时候,会抛出 HttpException 默认的异常的信息,根据resetful规则,我们需要根据自己的业务状态,定制自己的异常信息返回,在遇到具体的业务逻辑,抛出相应的异常,返回自己的业务信息。

遇到异常的时候返回的是html提示信息

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>ZeroDivisionError: division by zero // Werkzeug Debugger</title>
.....

继承扩展 HttpException:这个页面可以定制自己返回格式

from flask import request, json
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500
    msg = 'sorry,we make a mistake(*-_-*)!'
    error_code = 900

    def __init__(self, msg=None, code=None, error_code=None,
                 headers=None):
        if code:
            self.code = code
        if error_code:
            self.error_code = error_code
        if msg:
            self.msg = msg
        super(APIException, self).__init__(msg, None)

    @staticmethod
    def get_url_no_param():
        """
        获取接口路径
        :return:
        """
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]

    def get_body(self, environ=None):
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            request=request.method + ' ' + self.get_url_no_param()
        )

        text = json.dumps(body)
        return text

    def get_headers(self, environ=None):
        """Get a list of headers."""
        return [('Content-Type', 'json/application')]

    #返回的json数据格式 示例
    {
        "code":100,
        "msg":"success",
        "error_code":1001
    }

在具体的业务逻辑返回相应的状态即可(相当于直接抛出一个异常信息,显示自定义内容) 示例

@api.route('/register', methods=['POST'])
def create_client():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: __register_user_by_email
    }
    promise[form.type.data]()
    # 可以预知的异常
    return Success()

class Success(APIException):
    code = 201
    msg = 'ok'
    error_code = 1

优化:继承HttpException 只能捕获 http异常的信息,其它非预知的异常信息需要,进行全局的异常捕获 在app入口出配置

@app.errorhandler(Exception)
def framework_error(e):
    """
    全局捕获的异常,在flask1.0才有
    :param e:
    :return:
    """
    if isinstance(e, APIException):
        return e
    if isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        error_code = 1007
        return APIException(msg, code, error_code)
    else:
        # 调试模式
        if not app.config['DEBUG']:
            return ServerError(msg=e.description)
        else:
            raise e
# 一些程序非预知的异常信息,将统一抛出 ServerError信息,设置了一个开关,在debug模式返回默认的信息便于查看。

class ServerError(APIException):
    code = 500
    msg = 'sorry ,there is make a mistake(-_-)'
    error_code = 999
上一篇下一篇

猜你喜欢

热点阅读