1

Tornado uses classes which derive from tornado.web.RequestHandler to define post and get methods. I have created a request handler for the path r/action/*

Since there are different more concrete paths, like action/doThis and action/requestThat I have structured the get method with a if-then-else structure checking for the concrete request URI.

That seems very clumsy, is there a more sophisticated way to structure that, for instance with methods? Or would the Tornado way be to just define more RequestHandlers? I like the way bottle does it with Function Decorators, but since they are Python 3, this is not an option at the moment.

Mahoni
  • 7,088
  • 17
  • 58
  • 115

2 Answers2

5

Decorators are not limited to Python 3; I use bottle with 2.7 frequently (I prefer the decorator syntax and the lighter weight of bottle when prototyping interfaces, or when I don't find my implementation needing the class-based behavior of Tornado).

That said, if action/doThis and action/requestThat provide different behavior, would you be better served by defining them as separate routes? If they share some aspects of their behavior, you could always have both RequestHandler subclasses share a common base.

class HandleAction(tornado.web.RequestHandler):
    def take_appropriate_action(route):
        print("Responding to action/{}".format(route))


class HandleThis(HandleAction):
    def get(self):
        self.take_appropriate_action('doThis')


class HandleThat(HandleAction):
    def get(self):
        self.take_appropriate_action('requestThat')


app = tornado.web.Application([
    (r'/action/doThis', HandleThis),
    (r'/action/requestThat', HandleThat)
])
Matt Tenenbaum
  • 1,321
  • 10
  • 11
1

Similar Question and the first answer I would agree with. Because of the lack of features that Tornado provides you have to roll your own solutions or use somnething like Tornado Addons which would ease the annoyance of creating the necessary handlers and their associated routes.

from tornado_addons.route import route

@route( "/action/doThis" )
class HandleDoThis( Request ):
 pass

@route( "/action/requestThat" )
class HandleRequestThat:
 pass

app = tornado.web.Application( route.get_routes() )

This would make it much more viable to create separate handler classes for each of your RESTful resources. This would clean up your if statement worries.

Community
  • 1
  • 1
sean
  • 3,955
  • 21
  • 28