Search code examples
pythontornado

Tornado/Python – How do I avoid this repetition?


I am new to Tornado, and I have this simplified code for the purposes of this question:

class LoginHandler(BaseHandler):
    def get(self):
        error_message = None
        title = "Log in to your account"

        self.render("login.html", error_message=error_message, title=title)

    def post(self):
        #function and params excluded for brevity of question
        error_message = self.authenticate_user()
        title = "Log in to your account"

        self.render("login.html", error_message=error_message, title=title)

The self.render("login.html", error_message=error_message, title = title) as well as the title variable are repeated (seemingly unnecessarily) because otherwise, I get the error "Global variable 'title' or 'error_message' not defined," depending on whether I use post or get to render the page.

I have a different title for every page, and I was wondering how I can simply have one title variable and one self.render("login.html"...) per page handler (i.e., LoginHandler) that will work when either the get or post function is called. I don't like the verbatim repetition, but I am having trouble avoiding error messages when I don't do the same thing in both functions.

How can I solve this? Thank you.


Solution

  • You can avoid redeclaring the title and error_message variables by initiating them as class members. (I used the leading underscore _ in the variable name to indicate that this value should be private and is only to be used in this class.)

    class LoginHandler(BaseHandler):
        def __init__(self):
            # Call the BaseHandler's __init__ function to initialize parent's members
            BaseHandler.__init__()
            self._title = "Log in to your account"
    
        def get(self):
            self.render("login.html", error_message=None, title=self._title)
    
        def post(self):
            self.render("login.html", error_message=self.authenticate_user(), title=self._title)
    

    The added advantages of doing it this way is that you only need to change the title in one spot and you don't run the risk of getting a different title depending on whether the method was get or post.

    NOTE: It appears that in error_message is not necessary - it's only being used in a single case. The self.render() calls do not receive the same parameters and therefore are both necessary.