gpt4 book ai didi

python - Google App Engine 的独特验证器 (WTForms)

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:12 34 4
gpt4 key购买 nike

我正在尝试为 WTForms 创建一个与 Google App 引擎配合使用的独特验证器。我有一个名为“问题”的模型和一个名为“slug”的字段,我需要它是唯一的。我在 Stackoverflow 上发现了这个非常好的示例,但它使用了 SQLAlchemy。我想看看是否有人可以帮助我弄清楚如何让它与 Google App Engine 而不是 SQLAlchemy 一起使用。

SQLAlchemy 示例:Unique validator in WTForms with SQLAlchemy models

class Unique(object):
""" validator that checks field uniqueness """
def __init__(self, model, field, message=None):
self.model = model
self.field = field
if not message:
message = u'this element already exists'
self.message = message

def __call__(self, form, field):
check = self.model.query.filter(self.field == field.data).first()
if check:
raise ValidationError(self.message)

我认为“检查”行需要更改才能与 GAE 一起使用?但我并不是最擅长将此类内容传递给对象。

我知道 GAE 查询类似于... Question.query(Question.slug = slug)

最佳答案

我能够用这个做到这一点......

class UniqueValidator(object):
""" validator that checks field uniqueness """
def __init__(self, model, field, message=None):
self.model = model
self.field = field
if not message:
message = u'Existing element with the same value.'
self.message = message

def __call__(self, form, field):
existing = self.model.query(getattr(self.model,self.field) == field.data).get()
if 'id' in form:
id = int(form.id.data)
else:
id = None
if existing and (id is None or id != existing.key.id()):
raise ValidationError(self.message)

class QuestionEditForm(Form):
id = HiddenField('id')
question = TextField('Question', [validators.Required(),
validators.Length(min=4, max=225)])
slug = TextField('Slug', validators = [validators.Required(),
validators.length(max=200),
UniqueValidator(
Question,
'slug',
'Existing slug with the same value.'
)])`enter code here`

关于python - Google App Engine 的独特验证器 (WTForms),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695813/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com