Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

The other answer provided fixes it for you, but doesn't explain why.

This has nothing to do with GAE, or failure in python inheritance.

In your case the __init__ method is inherited by LoginHandler and always sets is_logged_in to False after the super call. This is expected behaviour of inheritence.

You problem is you are calling super in your __init__ before you set is_logged_in, which means whatever you do in your own initialize method you are immediately and unconditionally overriding it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top