在Google App Engine中引用属性内的模型类

时间:2013-05-14 22:15:00

标签: python google-app-engine

如何在属性验证器中引用模型类?

我的源代码如下。这是我的模型类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)

0 个答案:

没有答案