deffield_max_limit(max_length):defvalidate(s):iftype(s)!=str:raiseValidationError("The field must be String.")iflen(s)<=max_length:returnsraiseValidationError("The field cannot exceed %i characters."%max_length)returnvalidate# 解析请求参数时候验证长度parse.add_argument('username',type=field_max_limit(5),required=True)
fromflaskimportFlaskfromflask_restfulimportApi,Resource,reqparsefromwerkzeug.routingimportValidationErrorapp=Flask(__name__)api=Api(app)deffield_max_limit(max_length):defvalidate(s):iftype(s)!=str:raiseValidationError("The field must be String.")iflen(s)<=max_length:returnsraiseValidationError("The field cannot exceed %i characters."%max_length)returnvalidateclassLogin(Resource):defpost(self):parse=reqparse.RequestParser()parse.add_argument('username',type=field_max_limit(5),required=True)parse.add_argument('password',type=field_max_limit(20),required=True)args=parse.parse_args()print({'username':args.username,'password':args.password})return{'code':20000}api.add_resource(Login,'/login')