使用App Engine和Webapp的REST Web服务
我想在应用引擎上建立一个REST网络服务。目前我有这个:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class UsersHandler(webapp.RequestHandler):
def get(self, name):
self.response.out.write('Hello '+ name+'!')
def main():
util.run_wsgi_app(application)
#Map url like /rest/users/johnsmith
application = webapp.WSGIApplication([(r'/rest/users/(.*)',UsersHandler)]
debug=True)
if __name__ == '__main__':
main()
我希望当访问路径/rest/users时,可以获取到我所有的用户。我想我可以通过建立另一个处理程序来实现这个功能,但我想知道是否可以在这个处理程序内部完成。
1 个回答
14
当然可以——把你处理请求的部分的 get
方法改成
def get(self, name=None):
if name is None:
"""deal with the /rest/users case"""
else:
# deal with the /rest/users/(.*) case
self.response.out.write('Hello '+ name+'!')
然后把你的应用改成
application = webapp.WSGIApplication([(r'/rest/users/(.*)', UsersHandler),
(r'/rest/users', UsersHandler)]
debug=True)
换句话说,就是把你的处理器(handler)和你想要它处理的所有网址模式对应起来,并确保处理器的 get
方法能轻松区分这些网址(通常是通过它的参数来区分)。