Flask-restful: How to limit the length of a parameter

Created on 5 May 2017  ·  3Comments  ·  Source: flask-restful/flask-restful

def string6(str, type):
    if len(str) >= 6:
        return str
    raise ValidationError(type + "最少为6个字符")
def string11(str, type):
    if len(str) ==11:
        return str
    raise ValidationError(type + "必须为11个字符")
user_parse = reqparse.RequestParser()
user_parse.add_argument('username', type=string6, location='form', required=True)
user_parse.add_argument('phone', type=string11, help='请输入一个有效的手机号码!', location='form', required=True)

I know it is not standardized, is there a better way to do it?

Most helpful comment

Make a function that returns a function!

def min_length(min_length):
    def validate(s):
        if len(s) >= min_length:
            return s
        raise ValidationError("String must be at least %i characters long" % min)
    return validate


user_parse.add_argument('username', type=min_length(6), location='form', required=True)

All 3 comments

Make a function that returns a function!

def min_length(min_length):
    def validate(s):
        if len(s) >= min_length:
            return s
        raise ValidationError("String must be at least %i characters long" % min)
    return validate


user_parse.add_argument('username', type=min_length(6), location='form', required=True)
def min_length(min_length):
    def validate(s):
        if len(s) >= min_length:
            return s
        raise ValidationError("String must be at least %i characters long" % min)
    return validate

where is s source

I used a type of regex to limit the length of the string, something like this:

patch_args.add_argument('name', type=inputs.regex('^\w{1,256}$'), required=False, location="form")
Was this page helpful?
0 / 5 - 0 ratings

Related issues

quantwizard picture quantwizard  ·  6Comments

SubhabrataBanerji picture SubhabrataBanerji  ·  5Comments

lipis picture lipis  ·  3Comments

svvitale picture svvitale  ·  8Comments

dmikhaylov picture dmikhaylov  ·  5Comments