Thursday, May 22, 2014

Method-based URL dispatcher for the Tornado web server

Nice tip which allows to write methods instead of class for requestHandler

Method-based URL dispatcher for the Tornado web server

Here is the classic way
class Foo(tornado.web.RequestHandler): 
    def get(self): 
        self.write('foo') 
 
class Bar(tornado.web.RequestHandler): 
    def get(self): 
        self.write('bar') 
 
class SimonSays(tornado.web.RequestHandler): 
    def get(self): 
        say = self.get_argument("say") 
        self.write('Simon says, %s' % `say`) 
 
application = tornado.web.Application([ 
    (r"/foo", Foo), 
    (r"/bar", Bar), 
    (r"/simonsays", SimonSays), 
])

The MethodDispatcher way
class FooBar(MethodDispatcher): 
    def foo(self): 
        self.write("foo") 
 
    def bar(self): 
        self.write("bar") 
 
    def simonsays(self, say): 
        self.write("Simon Says, %s" % `say`) 
 
application = tornado.web.Application([ 
    (r"/.*", FooBar) 
])


Highlighted with : http://tohtml.com/python/

No comments:

Post a Comment