谷歌应用引擎数据存储的默认用户输入验证。
gae-validators的Python项目详细描述
版权所有©2014-2019,Brendan Doms
根据MIT license
GAE验证器
gae验证器为用户输入验证方法提供google app engine数据存储的智能默认值。
生成状态
工作原理
每个验证器只是一个接收字符串输入并返回(valid, value)
元组的方法。
valid
只是输入是否通过验证的布尔值。
value
是强制的、潜在优化的输入版本。
例如,字符串去掉了外部空白,而整数、布尔值和日期都作为各自的类型返回。
一些验证器有额外的参数来帮助配置如何进行验证。 默认情况下,这些都定义为符合 GAE properties。 理论上,只需更改配置参数就可以支持任何数据存储后端。
示例使用
程序的正常流程是从表单中获取一些用户输入,将其从请求中拉出,并对其进行验证。 如果所有字段的验证都通过,则更新数据存储,如果没有,则向用户返回有用的错误。 例如:
fromgae_validatorsimportvalidateEmailclassExampleHandler(webapp2.RequestHandler):defpost(self):form_email=self.request.get("email")is_valid,validated_email=validateEmail(form_email)ifis_valid:user.email=validated_emailuser.put()else:self.redirect("/user/update?errors=email")
可用验证器
下面是所有具有默认配置值的函数签名:
validateString(source,max_length=500,newlines=False,encoding='utf-8')validateRequiredString(source,max_length=500,newlines=False,encoding='utf-8')# same as above execpt that an empty string will failvalidateText(source,max_length=ONE_MB,newlines=True,encoding='utf-8')# ONE_MB is defined as 2 ** 20validateRequiredText(source,max_length=ONE_MB,newlines=True,encoding='utf-8')validateEmail(source)validateRequiredEmail(source)validatePhone(source)# returns the number in a good approximation of E.164 format# this should work exactly for numbers with country code 1 (US and Canada)# however it will not be correct in all cases for all countries# you'll need a different solution if you want full international supportvalidateRequiredPhone(source)validateUrl(source)# only http and https schemes are supportedvalidateRequiredUrl(source)validateChoices(source,choices)# choices should be an iterablevalidateRequiredChoices(source,choices)validateBool(source)# any value can be truthy or falsy# so there is no required version of validateBool, and it will never return an invalid resultvalidateInt(source,min_amount=-INT_SIZE,max_amount=INT_SIZE-1)# INT_SIZE is defined as a 64 bit signed integer, which means 2 ** 63validateRequiredInt(source,min_amount=-INT_SIZE,max_amount=INT_SIZE-1)validateFloat(source,min_amount=-INT_SIZE,max_amount=INT_SIZE-1)validateRequiredFloat(source,min_amount=-INT_SIZE,max_amount=INT_SIZE-1)validateDateTime(source,date_format="%Y-%m-%dT%H:%M",future_only=False,past_only=False)validateRequiredDateTime(source,date_format="%Y-%m-%dT%H:%M",future_only=False,past_only=False)validateDate(source,date_format="%Y-%m-%d",future_only=False,past_only=False)validateRequiredDate(source,date_format="%Y-%m-%d",future_only=False,past_only=False)validateTime(source,time_format="%H:%M")validateRequiredTime(source,time_format="%H:%M")