python - ndb.StructuredProperty 中的自动字段值

标签 python google-app-engine google-cloud-datastore app-engine-ndb endpoints-proto-datastore

我想将位置存储在 Google 的数据存储区中。每个条目应具有“sys”字段,其中应包含数据存储设置的信息。 我有下面的类模型,并且 WebService JSON 请求/响应看起来不错,但我必须手动设置值。看起来 auto_current_user_addauto_now_addauto_current_userauto_now 不会触发。

from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel


class Created(EndpointsModel):
    by = ndb.UserProperty(auto_current_user_add=True)
    on = ndb.DateTimeProperty(auto_now_add=True)


class Updated(EndpointsModel):
    by = ndb.UserProperty(auto_current_user=True)
    on = ndb.DateTimeProperty(auto_now=True)


class Sys(EndpointsModel):
    created = ndb.StructuredProperty(Created)
    updated = ndb.StructuredProperty(Updated)


class Location(EndpointsModel):
    name = ndb.StringProperty(required=True)
    description = ndb.TextProperty()
    address = ndb.StringProperty()
    sys = ndb.StructuredProperty(Sys)

当我提交创建请求 (location.put()) 时,我收到以下响应:

{
    "id": "4020001",
    "name": "asdf"
}

当我使用手动设置时:

location.sys = Sys(created=Created(on=datetime.datetime.now(),
                                   by=current_user),
                   updated=Updated(on=datetime.datetime.now(),
                                   by=current_user))
location.put()

我得到了预期的结果:

{
 "id": "4020002",
 "name": "asdf",
 "sys": {
  "created": {
   "by": {
    "auth_domain": "gmail.com",
    "email": "decurgia@XYZ"
   },
   "on": "2015-01-27T16:05:41.465497"
  },
  "updated": {
   "by": {
    "auth_domain": "gmail.com",
    "email": "decurgia@XYZ"
   },
   "on": "2015-01-27T16:05:41.465577"
  }
 }
}

如何获取这些字段(sys.created.onsys.created.bysys.updated.onsys.updated.by) 自动设置?

最佳答案

在我使用 StructuredProperty 进行的有限工作中,我发现它比简单地将属性直接插入到模型中更慢且更难使用。 NDB 似乎单独存储这些属性并在检索它们时执行“连接”。我的建议是使用“平面”模型:

class Location(EndpointsModel):
    name = ndb.StringProperty(required=True)
    description = ndb.TextProperty()
    address = ndb.StringProperty()
    created_by = ndb.UserProperty(auto_current_user_add=True)
    created_on = ndb.DateTimeProperty(auto_now_add=True)
    updated_by = ndb.UserProperty(auto_current_user=True)
    updated_on = ndb.DateTimeProperty(auto_now=True)

这应该会导致自动触发 auto_ 属性。

关于python - ndb.StructuredProperty 中的自动字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168682/

相关文章:

python - 从 GtkTreeView 获取完整文件路径

python - 如何查询 Google App Engine 数据存储并将结果传递到新页面?

python - 尝试从 docker 容器访问时,Datastore 返回 503

java - 在一个查询中查询不同的EntitySubclass

python - 将 Pandas Dataframe 列转换为一个热标签

python Pandas : How to alter one column that is (complicatedly) based on another?

python - 错误 UnboundLocalError : local variable 'currentpl' referenced before assignment:

google-app-engine - 如何在GAE中有效实现session?

python - App Engine 版本,内存缓存

google-app-engine - 如何使用 Python 后端通过 HTTPS POST 接收 id token ?