JSON serialization of Google App Engine models

后端 未结 14 2114
不知归路
不知归路 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: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]))
    

提交回复
热议问题