Search code examples
pythongoogle-app-engineinheritancewebapp2

How does python inheritance work with GAE?


So, I have wasted now about two hours in a bug that I assume has to do with inheritance problems in python and GAE.

I have 2 classes, BlogHandler, and the child, LoginHandler:

    class BlogHandler(webapp2.RequestHandler):    
        def __init__(self, request=None, response=None):
            super(BlogHandler, self).__init__(request, response)
            self.is_logged_in = False

        def initialize(self, *args, **kwargs):
            webapp2.RequestHandler.initialize(self, *args, **kwargs)
            logging.warning('Checking for cookie')

            if True:
                self.is_logged_in = True
                logging.warning('We are logged in!')
            else:
                logging.warning('We seem to be logged out')

    class LoginHandler(BlogHandler):    
        def get(self):
            logging.warning('Choose wisely!: + %s', self.is_logged_in)
            if self.is_logged_in:
                self.redirect(MAIN_URL)
            else:
                self.render("login.html")

Every time I get a GET request from a client, the initialize(self, *args, **kwargs) method will run in the father, and then the get(self): method will run on the child.

Now I want the father to share a variable with the child, the is_logged_in variable. I have to give a default value to the varible so I initialize it in the father's constructor as False

Then, when I run the initialize(self, *args, **kwargs) I check for a condition, which is always True, so it has 100% chance of changing the is_logged_in variable to True.

Back to the child, I check the value of the said variable and ... is is always False. I cannot understand this bug, specially because I know I am changing the value of the said variable. Here is a log:

WARNING  2014-05-09 22:50:52,062 blog.py:47] Checking for cookie
WARNING  2014-05-09 22:50:52,062 blog.py:51] We are logged in!
WARNING  2014-05-09 22:50:52,063 blog.py:116] Choose wisely!: + False
INFO     2014-05-09 22:50:52,071 module.py:639] default: "GET /blog/login HTTP/1.1" 200 795

Why is this happening? What am I not understanding?


Solution

  • Try changing:

    class BlogHandler(webapp2.RequestHandler):
        def __init__(self, request=None, response=None):
            self.is_logged_in = False
            super(BlogHandler, self).__init__(request, response)
    

    Putting your attribute before your call to super.