简体   繁体   English

使用Python的Google App Engine中的JSON响应

[英]JSON response in Google App Engine with Python

I want to build a REST service with Python and Google App Engine and have the following code: 我想使用Python和Google App Engine构建REST服务,并具有以下代码:

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? 如何将此模型的所有项目转换为JSON并以JSON的形式发送回去? I always get this Error: 我总是收到此错误:

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

I use now NDB instead of DB and the following code solved all my problems: 我现在使用NDB代替DB,以下代码解决了所有问题:

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)

Use db.to_dict to convert a model to a dictionary and then you can do json.dumps on it. 使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM