Nick Heiner
Nick Heiner

Reputation: 122422

Google App Engine: Users API acting oddly

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.

Upvotes: 1

Views: 253

Answers (1)

Emilien
Emilien

Reputation: 3051

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!

Upvotes: 1

Related Questions