python - 如何将临时信息附加到我的 appengine ndb 模型实例?

标签 python google-app-engine app-engine-ndb

我正在尝试为我的模型设置属性,

class Foo(ndb.Model):
  name = ndb.StringProperty()
  1. 从内存缓存中检索 Foo 对象
  2. 如果不在memcache中,则从数据库中查询。 在这里,我想将附加信息附加到 Foo 实例 foo.special_name = "don't persist this"
  3. 将此对象从内存缓存传递到我的自定义 JsonEncoder
  4. 将此对象转储到字典中,foo = {name:"hello",special_name:"don't persist this"}

AFAIK,我无法设置不是字段的 ndb.Model 类的属性。

我害怕使用ndb.Expando,因为我担心这个对象会被持久化并且special_name会被保存到我的数据库中。

foo 添加临时一次性值的最简洁方法是什么?

编辑:

>>> class Foo(ndb.Model):
  name = ndb.StringProperty()
>>> f = Foo()
>>> f.put()
Key('Foo', 26740114379063)
>>> f.bar = 123 
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> f
Foo(name=None)
>>> f.bar
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
>>> setattr(f, 'bar', 123)
>>> getattr(f, 'bar')
Traceback (most recent call last):
  File "/base/data/home/apps/shell/1.335852500710379686/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'

最佳答案

"I can't set attributes of ndb.Model classes that are not fields."

你为什么会这么想?模型实例只是对象,与 Python [*] 中的任何其他对象一样,您可以根据需要在它们上设置任意属性。

[*]:(只要类没有定义 __slots__,ndb.Model 没有定义)

关于python - 如何将临时信息附加到我的 appengine ndb 模型实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425251/

相关文章:

python - 如何根据Python中的字符拆分字符串列表

python - 使用 pycrypto 将 RSA key 保存到文件

google-app-engine - 如何通过 Google Cloud Pub/Sub API 接收长时间运行的操作结果

python - NDB 中 M 到 M 的结构化查询

python - 如何检查列表中的元素是否存在于另一个列表中

python - 使用 python mysql 连接器时如何使用变量作为属性名称

google-app-engine - 在 App Engine localhost 上启动 Go 服务器会抛出错误

java - 使用 appengine 避免指数爆炸和实体组写入速率限制

google-app-engine - App Engine - 带投影的 NDB 查询需要子属性吗?

google-app-engine - google.appengine.ext.ndb 和 gcloud.datastore 之间有什么区别?