• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
上海-悠悠
帮助1

前言

当接口请求参数不合法的,可以给前端返回报错原因,给个友好的返回消息,在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": "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实例中的选项的全局设置。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhhaeggc
系列文章
更多 icon
同类精品
更多 icon
继续加载