JSON serialization of Google App Engine models

后端 未结 14 2099
不知归路
不知归路 2020-12-04 04:59

I\'ve been searching for quite a while with no success. My project isn\'t using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model)

相关标签:
14条回答
  • 2020-12-04 05:56

    As mentioned by https://stackoverflow.com/users/806432/fredva, the to_dict works great. Here is my code i'm using.

    foos = query.fetch(10)
    prepJson = []
    
    for f in foos:
      prepJson.append(db.to_dict(f))
    
    myJson = json.dumps(prepJson))
    
    0 讨论(0)
  • 2020-12-04 05:57

    This is the simplest solution I found. It requires only 3 lines of codes.

    Simply add a method to your model to return a dictionary:

    class DictModel(db.Model):
        def to_dict(self):
           return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
    

    SimpleJSON now works properly:

    class Photo(DictModel):
       filename = db.StringProperty()
       title = db.StringProperty()
       description = db.StringProperty(multiline=True)
       date_taken = db.DateTimeProperty()
       date_uploaded = db.DateTimeProperty(auto_now_add=True)
       album = db.ReferenceProperty(Album, collection_name='photo')
    
    from django.utils import simplejson
    from google.appengine.ext import webapp
    
    class PhotoHandler(webapp.RequestHandler):
       def get(self):
          photos = Photo.all()
          self.response.out.write(simplejson.dumps([p.to_dict() for p in photos]))
    
    0 讨论(0)
提交回复
热议问题