Question

In my Super-Simple Tornado URL dispatcher:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Main MainHandler ")

class MainHandler1(tornado.web.RequestHandler):
    def get(self):
        self.write("Main MainHandler 1")

class api_v1(tornado.web.RequestHandler):
    def get(self):
        pass


if __name__ == "__main__":
    application = tornado.web.Application(handlers=[
        (r"/", MainHandler),
        (r"/main1/", MainHandler1),
        #Meta API from the Application URIs
        (r"/api/v1/", api_v1),
    ])


    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

How Can I access to handlers variable from class api_v1(tornado.web.RequestHandler). Is it possible?.

I want to show URLS pattern when user access to http://.../api/v1/

Thanks in advance.

Was it helpful?

Solution

The handler table that is passed in to the Application constructor is not available after the fact. Instead, save a copy before you create the application and make it available to your handlers:

handlers = [...]
# Unrecognized keyword arguments end up in Application.settings; recognized ones
# get eaten.  Pass the handler table in twice, once for the Application itself
# and once for settings.
app = Application(handlers, handler_table=handlers)

And in the handler use self.settings['handler_table']

OTHER TIPS

This is a slight hack, since it uses the private method Application._get_host_handlers, but that method hasn't changed in years so it might be safe:

class api_v1(tornado.web.RequestHandler):
    def get(self):
        handlers = self.application._get_host_handlers(self.request)
        response = json.dumps([spec.regex.pattern for spec in handlers])
        self.finish(response)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top