0

I want to build a REST service with Python and Google App Engine and have the following code:

Edited Code:

import webapp2
from google.appengine.ext import db
from google.appengine.api import users
import json

class Item(db.Model):

    author           = db.UserProperty(required=False)
    summary          = db.StringProperty(required=True)
    description      = db.StringProperty(multiline=True)
    url              = db.StringProperty()
    created          = db.DateTimeProperty(auto_now_add=True)
    updated          = db.DateTimeProperty(auto_now=True)
    dueDate          = db.StringProperty(required=True)
    finished         = db.BooleanProperty()

class GetAllItems(webapp2.RequestHandler):
    def get(self):
        item = Item(summary="Summary", dueDate="Date")
        item.put()

        allItems = Item.all()
        data = []
        for entry in allItems:
            data.append(db.to_dict(entry))

        self.response.out.write(json.dumps(entry))

app = webapp2.WSGIApplication(
    [
        ('/api/items', GetAllItems)
        ],
    debug=True)

How can i convert all items of this model into JSON and send it back as JSON? I always get this Error:

TypeError: <main.Item object at 0x0538B590> is not JSON serializable
0

2 Answers 2

2

I use now NDB instead of DB and the following code solved all my problems:

import decimal
import webapp2
from google.appengine.ext import ndb
import json
from google.appengine.api import users


class Item(ndb.Model):
    author = ndb.UserProperty(required=False)
    summary = ndb.StringProperty(required=True)
    description = ndb.StringProperty()
    url = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)
    updated = ndb.DateTimeProperty(auto_now=True)
    updated = ndb.StringProperty()
    dueDate = ndb.StringProperty(required=True)
    finished = ndb.BooleanProperty()


class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)


class GetAllItems(webapp2.RequestHandler):
    def get(self):
        item = Item(summary="Summary", dueDate="Date")
        item.put()

        text = json.dumps([i.to_dict() for i in Item.query().fetch()], cls=DateTimeEncoder)
        self.response.out.write(text)


app = webapp2.WSGIApplication(
    [
        ('/api/items', GetAllItems)
    ],
    debug=True)
Sign up to request clarification or add additional context in comments.

Comments

0

Use db.to_dict to convert a model to a dictionary and then you can do json.dumps on it.

class GetAllItems(webapp2.RequestHandler):
    def get(self):
        item = Item(summary="Summary", dueDate="Date")
        item.put()

        all_items = Item.all()
        data = []
        for entry in all_items:
            data.append(db.to_dict(entry))

        self.response(json.dumps(data))

2 Comments

With my model i get now this error: TypeError: <main.Item object at 0x0538B590> is not JSON serializable
This is weird. Try debugging the type of db.to_dict(entry)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.