views:

315

answers:

1

I want to build a REST web service on app engine. Currently i have this:

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()

And i would like to retreive for example all my users when the path /rest/users is accessed. I Imagine I can do this by building another handler, but I want to know if is possible to do it inside of this handler.

+4  A: 

Sure, you can -- change your handler's get method to

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+'!') 

and your application to

application = webapp.WSGIApplication([(r'/rest/users/(.*)', UsersHandler),
                                      (r'/rest/users', UsersHandler)]                                      
                                     debug=True)

In other words, map your handler to all the URL patterns you want it to handle, and make sure the handler's get method can distinguish among them easily (typically via its arguments).

Alex Martelli
You could also use two handlers - one for "/rest/users/" and one for "/rest/users/(.+)".
Nick Johnson
@Nick, sure, but the OP knows that, as he says "I can do this by building another handler, but I want to know if is possible to do it inside of this handler" -- so I didn't repeat what he'd just said;-).
Alex Martelli
Sorry, I missed that bit. :)
Nick Johnson