views:

98

answers:

1

I think I'm using the Users API incorrectly:

class BaseHandler(webapp.RequestHandler):
   user = users.get_current_user()

   def header(self, title):
     if self.user:
        render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
     else:
        render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})

link.html:

<p>
    <a href="{{href}}">{{text}}</a>
</p>

Sometimes it works, sometimes it doesn't. I will click the "log out" link 10 times in a row, and reload the page, and it will redirect me to the '/' page. Then, mysteriously, one of the times I'll be logged out. Logging in fails in essentially the same fashion. What's going on here?

Solved - This works:

class BaseHandler(webapp.RequestHandler):

    def __init__(self):
        self.user = users.get_current_user()

    def header(self, title):
        if self.user:
            render('Views/message.html', self, {'msg': "Welcome, %s" % self.user.nickname()})
            render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
        else:
            render('Views/link.html', self, {'text': 'Log in', 'href': users.create_login_url('/')})

It looks like I can have instance variables by referring to them as self.var_name in a function, but never declaring them on a class level. Odd.

+1  A: 

You are storing the result of users.get_current_user() in the variable called user, but then your if checks the value of self.user, which is not the same variable.

Use the same variable name and all should be fine!

Emilien
Sorry, it looks like I didn't include enough code initially. `self.user` is being checked from within a function, whereas `user` is stored at the class level.
Rosarch