views:

50

answers:

1

I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment.

The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a _template_data dictionary, for convenience of subclasses.

class BasePage(webapp.RequestHandler):
    _user = users.get_current_user()
    _login_logout_link = None
    if _user:
        _login_logout_link = users.create_logout_url('/')
    else:
        _login_logout_link = users.create_login_url('/')

    _template_data = {}
    _template_data['login_logout_link'] = _login_logout_link
    _template_data['user'] = _user

    def render(self, templateName, templateData):
        path = os.path.join(os.path.dirname(__file__), 'Static/Templates/%s.html' % templateName)
        self.response.out.write(template.render(path, templateData)) 

Here is one such subclass:

class MainPage(BasePage):
    def get(self):
        self.render('start', self._template_data)

The login/logout link is displayed fine, and going to the correct devserver login/logout page. However, it seems to have no effect - the server still seems to think the user is logged out. What am I doing wrong here?

+2  A: 

I believe the problem is the _user attribute.

Currently, the _user attribute is bound when the module containing the class is imported (probably when the application starts). You need to get the current user for each request.

I would rewrite into something like:

class BasePage(webapp.RequestHandler):
    def render(self, template_name, data={}):
        template_data = {}
        user = template_data["user"] = users.get_current_user()
        template_data["login_logout_link"] = users.create_logout_url() if user else users.create_login_url()
        template_data.update(data)
        path = os.path.join(os.path.dirname(__file__), 'Static', 'Templates', '%s.html' % template_name)
        self.response.out.write(template.render(path, template_data)

The templates would then always get the values user and login_logout_link sent in. In a subclass, you can pass extra values to the template using the data argument (template_data.update(data) updates the template_data dictionary with the key/value pairs from the data dictionary).

Subclass example:

class MainPage(BasePage):
    def get(self):
        self.render('start', data={"now": datetime.now()})
codeape
Indeed. This works. Thanks.
Rosarch