【问题标题】:ListProperty with GoogleAppEngine使用 GoogleAppEngine 的 ListProperty
【发布时间】:2012-11-26 06:10:06
【问题描述】:

如何使用 Google App Engine 分配 ListProperty?

    name = self.request.get("name")
    description = self.request.get("description")
    list = '''insert code here'''

我希望列表像字典一样工作,Google App Engine 是否可以,如果可以,如何:

[wordone:分数; wordtwo : 分数; wordthree : 分数]

^我想让list属性存储一些这样的数据,怎么可能?

【问题讨论】:

    标签: python google-app-engine web-applications


    【解决方案1】:

    您实际上无法将真正的字典存储为 ListProperty 中的类型(它仅支持数据存储属性类型,dict 不是其中之一),因此您将无法获得您正在寻找的行为。所有数据是否都相同(即每个元素代表一个单词分数)?假设将每个单词作为其自己的属性存储在模型上是没有意义的,一个“肮脏”的解决方案是创建一个str 类型的ListProperty,然后将单词和分数作为单独的元素附加。然后,当您在列表中搜索一个单词时,您将返回该单词索引位置的值 + 1。这看起来像:

    class MyEntity(db.Model):
      name = db.StringProperty()
      description = db.TextProperty()
      word_list = db.ListProperty()
    

    然后你可以添加类似的词:

    new_entity = MyEntity()
    new_entity.word_list = ['word1', 1, 'word2', 2, 'word3', 10]
    

    然后您可以查询特定实体,然后检查其word_list 属性(一个列表),查找您的目标词并将元素返回到它后面的一个位置。


    更复杂的建议

    但是,如果这不是一个选项,您可以考虑创建另一个看起来像这样的模型(比如说WordScore):

    class WordScore(db.Model):
      word = db.StringProperty()
      score = db.IntegerProperty()
    

    然后,当您需要添加新分数时,您将创建一个WordScore 实例,填写属性,然后将其分配给适当的实体。我还没有测试过这些,但想法是这样的:

    # Pull the 'other' entity (this would be your main class as defined above)
    q = OtherEntity.all()
    q.filter('name =', 'Someone')
    my_entity = q.get()
    
    # Create new score
    ws = WordScore(parent=my_entity)
    ws.word = 'dog'
    ws.score = 2
    ws.put()
    

    然后,您可以通过执行类似操作(同样,目前完全未经测试 - 请注意 :))为“某人”提取 dog 的分数:

    # Get key of 'Someone'
    q = OtherEntity.all()
    q.filter('name =', 'Someone')
    my_entity = q.get().key()
    
    # Now get the score
    ws = WordScore.all()
    ws.filter('word = ', 'dog').ancestor(my_entity)
    word_score = ws.get().score
    

    【讨论】:

      【解决方案2】:

      更改为 NDB 并使用 Pickle 属性:

      Value 是一个 Python 对象(例如列表、字典或字符串),可以使用 Python 的 pickle 协议进行序列化; Datastore 将 pickle 序列化存储为 blob。默认情况下未编入索引。

      NDB Properties

      那么就可以直接使用了:

      class table(ndb.Model):
          data_dict = ndb.PickleProperty(default = {})
      

      然后

      dd = table()
      dd.data_dict['word_one'] = "Some_Score"
      

      【讨论】:

      • +1 - 需要对 NDB 进行更多试验,这看起来是一个令人信服的理由!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      相关资源
      最近更新 更多