我想使用Python和Google App Engine构建REST服务,并使用以下代码:
编辑代码:
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)
如何将此模型的所有项目转换为JSON并将其作为JSON发回? 我总是得到这个错误:
TypeError: <main.Item object at 0x0538B590> is not JSON serializable
答案 0 :(得分:2)
我现在使用NDB而不是DB,以下代码解决了我所有的问题:
~/.metadata/.plugins/org.python.pydev.debug/coverage/.coverage.0
答案 1 :(得分:0)
使用db.to_dict
将模型转换为字典,然后您可以对其进行json.dumps
。
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))