[英]What is the easiest way to convert nested Datastore Entities to a Python dict?
I've tried reading the docs here and following the answers here but neither worked.我试过在这里阅读文档并按照这里的答案进行操作,但都没有奏效。
Here's what I put into datastore:这是我放入数据存储区的内容:
{'a': 'b', 'c': {'d': 'f'}}
If I query it I get:如果我查询它,我会得到:
<Entity('MyKind', 1232141232id) {'a': 'b', 'c': <Entity {'d': 'f'}>}>
I'm using google-cloud-python (which is recommended in docs) instead of ndb so I can't use:我正在使用google-cloud-python (在文档中推荐)而不是ndb所以我不能使用:
from google.appengine.ext import db
db.to_dict(entity)
If I try to cast dict(results[0])
I get:如果我尝试投射
dict(results[0])
我得到:
{'a': 'b', 'c': <Entity {'d': 'f'}>}
^^ This is almost what I need except for the nested Entity. ^^ 这几乎是我需要的,除了嵌套实体。
Any recommendations for the best way to do this?有关执行此操作的最佳方法的任何建议? It seems like there would be a function for this but I just can't find it.
似乎会有一个功能,但我找不到它。
So Entity
itself inherits from dict
and adds only a few functions on top所以
Entity
本身继承了dict
,只在上面添加了几个函数
https://googleapis.dev/python/datastore/latest/_modules/google/cloud/datastore/entity.html#Entity https://googleapis.dev/python/datastore/latest/_modules/google/cloud/datastore/entity.html#Entity
Your json
solution could be fine, but it depends on what the goal is.您的
json
解决方案可能没问题,但这取决于目标是什么。 If you're ultimately just trying to convert to json then it should be fine, but you're not capturing entity.key
and maybe that's something you want.如果您最终只是尝试转换为 json,那么应该没问题,但是您没有捕获
entity.key
,也许这就是您想要的。 Also i think json
will fail for datetime
objects and foreign keys unless you explicitly handle those somehow.此外,我认为
json
将无法处理datetime
对象和外键,除非您以某种方式明确处理它们。
You probably need to build a util function like this:您可能需要像这样构建一个 util 函数:
def _coerce_value(v):
if isinstance(v, Entity):
return_value[k] = entity_to_dict(v)
elif isinstance(v, Key):
return v.id # or do something else here
return v
def entity_to_dict(entity):
return_value = {}
if entity.key:
return_value['key'] = _coerce_value(entity.key)
for k, v in entity.iteritems():
if isinstance(v, list): # handle repeated properties
return_value[k] = [_coerce_value(i) for i in v]
else:
return_value[k] = _coerce_value(v)
return return_value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.