Store a list of dictionaries in GAE

前端 未结 3 652
抹茶落季
抹茶落季 2020-12-21 06:30

I have a list of about 20 objects and for each object I return a list of 10 dictionaries.
I am trying to store the list of 10 dictionaries for each object in the list on

3条回答
  •  臣服心动
    2020-12-21 06:48

    When I deal with data types that are not directly supported by Google App Engine like dictionaries or custom data type, I usually adopt the handy PickleProperty.

    from google.appengine.ext import db
    import pickle
    
    class PickleProperty(db.Property):
        def get_value_for_datastore(self, model_instance):
            value = getattr(model_instance, self.name, None)
            return pickle.dumps(value)
    
        def make_value_from_datastore(self, value):
            return pickle.loads(value)
    

    Once declared the PickleProperty class in your commons.py module, you can use it to store your custom data with something like this:

    from google.appengine.ext import db
    from commons import PickleProperty
    
    class Tw(db.Model):
      tags = PickleProperty()
      ip = db.StringProperty()
    
    entities = []
    for city in lst_of_cities:
      dict_info = hw12.twitter(city)
      entity = Tw()
      entity.tags = dict_info
      entity.ip = self.request.remote_addr
      entities.append(entity)
    
    db.put(entities)
    

    To retrieve the data back go with:

    entity.tags
    

提交回复
热议问题