仅使用Google App Engine、webapp2和Python创建API?
是否可以在Google App Engine上仅使用webapp2和Python创建API 例如,让我们看看我的路由仅使用Google App Engine、webapp2和Python创建API?,python,google-app-engine,google-cloud-platform,google-cloud-python,Python,Google App Engine,Google Cloud Platform,Google Cloud Python,是否可以在Google App Engine上仅使用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
是由以下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页面)
这是可能的还是推荐的?您不必返回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)
更新:例如,使用POST
方法询问OP:
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)
如果我们要发布数据呢?我们怎样才能做到这一点?如果您愿意,您会在回答中提供一个示例吗?感谢您提供这个示例,它演示了如何处理GET方法。API的另一部分应该能够处理其他http方法;我们如何配置它来处理POST或DELETE方法?我不知道我是否理解。处理POST方法是最基本的。你应该读到我不想花时间做学生的家庭作业。请参阅更新的答案。需要注意的一点是,当使用webapp2处理带有参数的POST请求时,我们使用self.request.get('some_field'),而当我们的应用程序接收restful POST请求时,我们似乎使用self.request.body访问发送的数据。