只使用googleappengine、webapp2和Python创建API?

2024-06-25 22:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在googleappengine上只使用webapp2和Python就可以创建API吗?在

例如,我的路由/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页面)。在

这是可能的还是建议的?在


Tags: selfapi路由getdefasquerypost
2条回答

你不必返回HTML页面。您可以返回一个JSON,甚至是一个字符串,因为它是您托管的代码。你可以很容易地用你的应用引擎发送一个URL来响应REST调用。在

您可以在查询之外构建一个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方法为例:

^{pr2}$

相关问题 更多 >