I'm pretty new in Tornado. Can I use something like below?
Class
class HomeHandler(BaseHandler):
def get(self):
return self.render("home.html")
def login(self):
return self.render("login.html")
Routes
(r"/", HomeHandler),
(r"/login", HomeHandler.login, dict(db=db)),
This is not working. I tried to use HomeHandler.login()
, but am not sure how to pass the required references (which should be similar to self).
I appreciate your help. Thanks
Tornado uses the concept of "handlers", which, well, handle requests at a certain path. Handlers are classes. Internally Tornado selects a method from these classes corresponding to HTTP verb used in the request.
In your case, you have 2 paths: /
and /login
, let's call them "Home" and "Login' respectively. Now, you need to have 2 handlers: HomeHandler
and LoginHandler
and assign them to corresponding routes...
Routes:
(r"/", HomeHandler),
(r"/login", LoginHandler, {"db": db})
Handler classes:
class HomeHandler(BaseHandler):
def get(self):
# Will work for GET yoursite.com/, e.g. when opened in a browser
# The next line will render a template and return it to the browser
self.render("home.html")
class LoginHandler(BaseHandler):
def initialize(self, db):
# That `db` from route declaration is passed as an argument
# to this Tornado specific method
self.db = db
def get(self):
# Will work for GET yoursite.com/login, e.g. when opened in a browser
# You may use self.db here
# The next line will render a template and return it to the browser
self.render("login.html")
def post(self):
# Will work for POST yoursite.com/login, e.g. when the data
# from the form on the Login page is sent back to the server
# You may use self.db here
return