zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Flask 学习-35.restful-full 自定义错误内容 error_msg 使用

错误restful学习 使用 Error 自定义 内容 msg
2023-06-13 09:12:01 时间

前言

当接口请求参数不合法的,可以给前端返回报错原因,给个友好的返回消息,在add_argument() 中可以通过help 参数来定义

错误信息

每个字段的错误消息可以使用 help 参数(RequestParser.add_argument)进行自定义。 如果未提供help 参数,则该字段的错误消息将是类型错误本身的字符串表示形式。如果help提供,则错误消息将是 的值help。

class Register(Resource):

    @staticmethod
    def password_validate(value, name):
        if len(value) < 6 or len(value) > 16:
            raise ValueError(name + ' length must be 6-16')
        return value

    def post(self):
        # 校验入参
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, type=str,  nullable=False)
        parser.add_argument('password', required=True, type=self.password_validate,
                            nullable=False, help='password invalid')
        args = parser.parse_args()
        print(f'请求入参:{args}')

在上面示例中username 参数没有给help 参数,password 参数给了help 如果不传username 参数,返回内容是错误本身的字符串表示形式

HTTP/1.1 400 BAD REQUEST
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 14:31:28 GMT
Content-Type: application/json
Content-Length: 130
Connection: close

{
    "message": {
        "username": "Missing required parameter in the JSON body or the post body or the query string"
    }
}

如果不传password 参数,返回内容就是给的help 值

HTTP/1.1 400 BAD REQUEST
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 14:33:53 GMT
Content-Type: application/json
Content-Length: 66
Connection: close

{
    "message": {
        "password": "password invalid"
    }
}

error_msg 变量使用

前面使用help 的时候是一个写死的值,当密码少于6位或大于16位的时候,也是返回password invalid,这样就比较抽象。 help可能包含一个插值标记 ,{error_msg}它将被替换为类型错误的字符串表示形式。这允许在保留原始错误的同时自定义消息

parser.add_argument('password', required=True, type=self.password_validate,
                            nullable=False, help='password invalid: {error_msg}')

当password 参数小于6位时返回

HTTP/1.1 400 BAD REQUEST
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 14:39:11 GMT
Content-Type: application/json
Content-Length: 87
Connection: close

{
    "message": {
        "password": "password invalid: password length must be 6-16"
    }
}

bundle_errors 错误处理

RequestParser 处理错误的默认方式是在发生第一个错误时中止。当您有可能需要一些时间来处理的论点时,这可能会很有用。但是,通常最好将错误捆绑在一起并一次性发送回客户端。 可以在 Flask 应用程序级别或特定的 RequestParser 实例上指定此行为。要使用捆绑错误选项调用 RequestParser,请传入参数bundle_errors。例如

from flask_restful import reqparse

parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('foo', type=int, required=True)
parser.add_argument('bar', type=int, required=True)

# If a request comes in not containing both 'foo' and 'bar', the error that
# will come back will look something like this.

{
    "message":  {
        "foo": "foo error message",
        "bar": "bar error message"
    }
}

# The default behavior would only return the first error

parser = RequestParser()
parser.add_argument('foo', type=int, required=True)
parser.add_argument('bar', type=int, required=True)

{
    "message":  {
        "foo": "foo error message"
    }
}

BUNDLE_ERRORS 可以作为全局配置参数,例如

from flask import Flask

app = Flask(__name__)
app.config['BUNDLE_ERRORS'] = True

警告: BUNDLE_ERRORS是覆盖bundle_errors 单个RequestParser实例中的选项的全局设置。

2022年第 12期《python接口web自动化+测试开发》课程,9月17号开学!

本期上课时间:2022年9月17号 - 2022年12月17号,周六周日上午9:00-11:00

报名费:报名费3000一人(周期3个月)

联系微信/QQ:283340479