【问题标题】:Parsing datastore Entity in Python efficiently在 Python 中有效地解析数据存储实体
【发布时间】:2019-03-08 08:26:29
【问题描述】:

所以现在,数据存储区ds.query(kind='users') 以以下形式向我返回响应:

<Entity(u'users', 5633378543992832L) {u'username': u'xyz', u'user_ip': '127.0.0.1', u'name': u'xyz', u'password': 'something', u'register_date': datetime.datetime(2019, 3, 8, 5, 50, 1, 443212, tzinfo=<UTC>)}>

虽然我可以这样迭代它:

result = {}
for oneItem in query.fetch():
    # oneItem is Entity iterable as shown above
    for oneProp in oneItem:
        result[oneProp] = oneItem[oneProp]

并通过something = result['password']访问任何属性

效果很好,但效率极低。有什么方法可以直接访问任何特定属性而不使用 for 循环或其他数据结构?类似于访问 JSON 中的值。

我正在使用from google.cloud import datastore

【问题讨论】:

  • 你想在你的例子中说明什么?您的 for 循环不断用下一个实体覆盖 result 中的值。您实际上只是在这样做:result = query.fetch()[-1]
  • 啊,是的,在我的情况下,它只会有一个我不能或不知道如何直接访问的实体。 query.fetch() 不支持索引。如果是这样,我不会发布这个问题。

标签: firebase nosql google-cloud-datastore datastore


【解决方案1】:

理想情况下,您将通过键检索所需的对象,而不是加载整个表。

为您提供准确的代码有点困难,因为我不知道您使用哪个库来访问数据存储。我一直用ndb,但你好像在用这个:

https://googleapis.github.io/google-cloud-python/latest/datastore/index.html

要按键获取,你会这样做:

from google.cloud import datastore
from google.cloud.datastore.key import Key
ds = datastore.Client()
oneItem = ds.get(Key(u'users', 5633378543992832L, project=project))

然后在这一点上,只需与它互动oneItem['password']

id 5633378543992832L 应该从当前会话中提供给您。因此,您只需要在会话创建期间进行查询。像这样的:

def create_session(username, raw_password):
    client = datastore.Client()
    query = client.query(kind=u'users')
    query.add_filter('username', '=', username)
    query.add_filter('password', '=', _your_password_hash_function(raw_password))
    results = query.fetch(1)
    if results:
        return _create_session_for_user(results[0])
    raise Exception("Invalid username/password")

您需要为上述查询添加一个索引才能工作。您似乎没有使用应用引擎,因此您可能必须通过 Web 控制台添加索引

【讨论】:

  • 谢谢。它工作......在本地。但事实证明,GAE 只支持标准环境中的 ndb,无论如何这两者似乎更好。
猜你喜欢
  • 2023-03-14
  • 2012-07-15
  • 2018-02-03
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2017-02-18
相关资源
最近更新 更多