8

有没有一种在数据存储中存储 Python 字典的好方法?我想做如下的事情:

from google.appengine.ext import db

class Recipe(db.Model):
  name = db.StringProperty()
  style = db.StringProperty()
  yeast = db.StringProperty()
  hops = db.ListofDictionariesProperty()

当然,最后一行实际上不起作用。我需要 hops 成为键值对列表,其中键始终是字符串,值可以是字符串、整数或浮点数,但我看不到任何可以让我在属性类

4

7 回答 7

7

序列化 dict withrepr是一个很好的方法。然后,您可以使用“安全评估”重新构建它eval,或者如果您不信任数据,则可以使用“安全评估”。

repr 优于 pickling 的一个优点是数据在数据库中是可读的,甚至在绝望的情况下也可以查询。

于 2009-11-11T18:09:30.787 回答
7

你可以使用 json

于 2009-11-11T19:44:58.957 回答
2

您可以腌制字典并将其存储为 StringProperty。

于 2009-11-11T18:06:11.420 回答
2

我很确定没有办法存储 Python 字典。但是为什么不把你想要的东西放在啤酒花中作为第二个模型呢?

此外,正如 John 所提到的,您可以使用 pickle,但是(如果我错了,请纠正我)将其存储为Blob值。

于 2009-11-11T18:09:36.980 回答
1

您的选择基本上是使用 pickle,使用 db.Expando 并使 dict 中的每个键成为一个单独的属性,或者在读取时使用一个 StringListProperty 键和一个值,然后 zip() 将它们返回到 dict。

于 2009-11-11T18:10:24.807 回答
1

您可以使用JsonProperty。Value 是一个 Python 对象(例如一个列表或一个字典或一个字符串),可以使用 Python 的 json 模块进行序列化;Cloud Datastore 将 JSON 序列化存储为 Blob。默认情况下未编制索引。可选关键字参数:压缩。

from google.appengine.ext import ndb

class Article(ndb.Model):
    title = ndb.StringProperty(required=True)
    stars = ndb.IntegerProperty()
    tags = ndb.StringProperty(repeated=True)
    info = ndb.JsonProperty()
于 2018-08-17T22:59:09.070 回答
0

我是这样做的:

class MyEntity(db.Model):
    dictionary_string = db.StringProperty()

payload = {{}...{}}

# Store dict
my_entity = MyEntity(key_name=your_key_here)
my_entity.dictionary_string = str(payload)
my_entity.put()

# Get dict
import ast
my_entity_k = db.Key.from_path('MyEntity', your_key_here)
my_entity = db.get(my_entity_k)
payload = ast.literal_eval(my_entity.dictionary_string)
于 2013-05-15T08:54:37.810 回答