您如何在属性验证器中引用模型类?
我的源代码如下。这是我的模型类的属性之一User
。问题在第 4 行,其中self
给出了关键字。我的目标是将User
模型类传递给验证器(它将使用它来搜索类对象以验证登录名是否具有唯一值),但我不知道如何引用该类。self
当然行不通。
class User(db.Model):
(...)
login = db.StringProperty(
required=True,
validator=combine_validators(
validate_uniqueness_fun(self, "login", LoginNotAvailable),
validate_string_fun(
LOGIN_MIN_LENGTH,
LOGIN_MAX_LENGTH,
LOGIN_VALID_REGEX,
LoginInvalidLength,
LoginInvalidFormat
)
)
)
(...)
以及属性中使用的函数。validate_string_fun()
没那么重要,但类似地,它返回验证器函数,该函数将属性值作为唯一参数。
def combine_validators(*validators):
"""
Accepts any number of validators (validating functions) which it combines into
one validator. The constructed function runs each given validator with that
value.
"""
return functools.partial(
_combine_validators,
validators_list=[v for v in validators]
)
def _combine_validators(value, validators_list):
for validator in validators_list:
validator(value)
def validate_uniqueness_fun(model, property_name, not_unique_exception):
"""
Arguments:
* model: subclass of google.appengine.ext.db.Model
* property_name: string
* property_not_unique: sub-clas of PropertyNotUnique
Returns a function that given a value validates it's uniqueness. If in the
property_name of the model class there already is a value equal to the
given one, it raises property_not_unique exception.
"""
return functools.partial(
_validate_uniqueness,
model=model,
property_name=property_name,
not_unique_exception=not_unique_exception
)
def _validate_uniqueness(property_value, model, property_name, not_unique_exception):
query = model.all().filter(property_name, property_value)
if (query.get()):
raise not_unique_exception(property_value)