gpt4 book ai didi

python - Google App Engine 模型的自定义键 (Python)

转载 作者:太空狗 更新时间:2023-10-29 17:45:40 25 4
gpt4 key购买 nike

首先,我对 Google App Engine 比较陌生,所以我可能做了一些愚蠢的事情。

假设我有一个模型 Foo:

class Foo(db.Model):
name = db.StringProperty()

我想使用 name 作为每个 Foo 对象的唯一键。这是怎么做到的?

当我想获取一个特定的 Foo 对象时,我目前在数据存储中查询所有具有目标唯一名称的 Foo 对象,但查询速度很慢(加上它是一个创建每个新的 Foo 时,很难确保 name 是唯一的。

必须有更好的方法来做到这一点!

谢谢。

最佳答案

我以前在一个项目中使用过下面的代码。只要您的键名所基于的字段是必需的,它就会起作用。

class NamedModel(db.Model):
"""A Model subclass for entities which automatically generate their own key
names on creation. See documentation for _generate_key function for
requirements."""

def __init__(self, *args, **kwargs):
kwargs['key_name'] = _generate_key(self, kwargs)
super(NamedModel, self).__init__(*args, **kwargs)


def _generate_key(entity, kwargs):
"""Generates a key name for the given entity, which was constructed with
the given keyword args. The entity must have a KEY_NAME property, which
can either be a string or a callable.

If KEY_NAME is a string, the keyword args are interpolated into it. If
it's a callable, it is called, with the keyword args passed to it as a
single dict."""

# Make sure the class has its KEY_NAME property set
if not hasattr(entity, 'KEY_NAME'):
raise RuntimeError, '%s entity missing KEY_NAME property' % (
entity.entity_type())

# Make a copy of the kwargs dict, so any modifications down the line don't
# hurt anything
kwargs = dict(kwargs)

# The KEY_NAME must either be a callable or a string. If it's a callable,
# we call it with the given keyword args.
if callable(entity.KEY_NAME):
return entity.KEY_NAME(kwargs)

# If it's a string, we just interpolate the keyword args into the string,
# ensuring that this results in a different string.
elif isinstance(entity.KEY_NAME, basestring):
# Try to create the key name, catching any key errors arising from the
# string interpolation
try:
key_name = entity.KEY_NAME % kwargs
except KeyError:
raise RuntimeError, 'Missing keys required by %s entity\'s KEY_NAME '\
'property (got %r)' % (entity.entity_type(), kwargs)

# Make sure the generated key name is actually different from the
# template
if key_name == entity.KEY_NAME:
raise RuntimeError, 'Key name generated for %s entity is same as '\
'KEY_NAME template' % entity.entity_type()

return key_name

# Otherwise, the KEY_NAME is invalid
else:
raise TypeError, 'KEY_NAME of %s must be a string or callable' % (
entity.entity_type())

然后您可以像这样修改您的示例模型:

class Foo(NamedModel):
KEY_NAME = '%(name)s'
name = db.StringProperty()

当然,在您的情况下,这可以大大简化,将 NamedModel__init__ 方法的第一行更改为类似以下内容:

kwargs['key_name'] = kwargs['name']

关于python - Google App Engine 模型的自定义键 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2465675/

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