flask参数校验自定义返回

parser = RequestParser()
parser.add_argument('name', type=str, required=True, location='json')
args = parser.parse_args()

上面是默认情况,如果参数校验出错,会返回:

{
    "message": {
        "name": "Missing required parameter in the JSON body"
    }
}

这可能不满足项目接口返回到要求,需要进行改造:

from flask_restful.reqparse import Argument,RequestParser


#继承Argument,重写handle_validation_error
class APIArgument(Argument):
    def __init__(self, *args, **kwargs):
        super(APIArgument, self).__init__(*args, **kwargs)

    def handle_validation_error(self, error, bundle_errors):
        error_msg = self.help.format(error_msg=str(error)) if self.help else str(error)
        if bundle_errors:
            return error, {self.name: error_msg}
        return abort(Response(
            json.dumps({"errcode": 400, "errmsg": f"{self.name} : {error_msg}"}),
            mimetype="application/json",
            status=200,
        ))

class xxx(Resource):
    @staticmethod
    def validate_email(value, name):
        if re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', value):
            return value
        else:
            raise ValueError(f'请输入正确的邮箱')

	parser = RequestParser(APIArgument) # 使用自定义的Argument
	parser.add_argument('name', type=str, required=True, location='json')
	parser.add_argument('email', type=self.validate_email, required=True, location='json')
	args = parser.parse_args()

改造后,参数验证失败的返回是:

{
    "errcode": 400,
    "errmsg": "name : Missing required parameter in the JSON body"
}

你可能感兴趣的:(flask,python,后端)