仅使用Google App Engine,webapp2和Python创建API?

是否可以在Google App Engine上仅使用webapp2和
Python创建API?

例如,让我的route / post / 123由此RequestHandler处理:

class ShowPosts(webapp2.RequestHandler):
    def get(self):
        posts = Post.query().fetch()
        # return the post as data (JSON) here as response 

当客户端向/ post / 123发出一个restful请求时,可以返回数据对象(而不是呈现的html页面).

这是可能的还是推荐的?

最佳答案 您可以从查询中构建python列表或dict对象,然后将其作为JSON对象发送,并将其作为响应发送.尝试这样的事情:

import json

posts     = Post.query()
post_json = []

for post in posts:
    post_dict = {
        'name' : post.name,
        'city' : post.city,
        'state': post.state
    }
    post_json.append( post_dict )

return json.dumps(post_json)

更新:OP问POST示例:

import json

class ShowPosts(webapp2.RequestHandler):
    def get(self):
        posts = Post.query()
        post_json   = []

        for post in posts:
            post_dict = {
                'name' : post.name,
                'city' : post.city,
                'state': post.state
            }

            post_json.append( post_dict )

        return json.dumps(post_json) 

    def post(self):
        posts = Post.query()
        post_json   = []

        for post in posts:
            post_dict = {
                'name' : post.name,
                'city' : post.city,
                'state': post.state
            }

            post_json.append( post_dict )

        post_json.append(
            {
                'posted_name': self.request.get('name'),
                'posted_msg': self.request.get('msg')
            }
        )
        return json.dumps(post_json) 
点赞