开发者

Access user's OpenID info in templates on Google app engine (tipfy)

I'm using the OpenID authentication that's built into Google app engine and trying to make the currently signed in user's information automatically available in templates.

Doing it manually might be something like:

from google.appengine.api import users
from tipfy import RequestHandler
from tipfy.ext.jinja2 import render_response

def WhateverHandler(RequestHandler):
    def get(self):
        user = users.get_current_user()
        return render_response('template_name.html', user=user)
        # great, now I can use {{ user.nickname }} or whatever in the template
开发者_JAVA百科

I don't want to write this code in every request handler so expecting to be able to add some kind of middleware to take care of it (and I'm mostly guessing here):

from google.appengine.api import users

class GoogleUsersMiddleware(object)

    def post_dispatch(self, handler, response):
        user = users.get_current_user()
        # now somehow add user to the response?

        return response

Any ideas? I've tried looking at how tipfy's SessionMiddleware works but don't quite get it.

Cheers.


You can create a subclass of RequestHandler that retrieves the current user automatically on __init__. Also you can add methods to that subclass to customize template rendering. I don't think Middleware is the right solution for this problem.

from google.appengine.api import users
from tipfy import RequestHandler
from tipfy.ext.jinja2 import render_response

class UserPageHandler(RequestHandler):
    def __init__(self, app, request):
        super(UserPageHandler, self).__init__(app, request)

        self.user = users.get_current_user()

    def user_response(self, template_name):
        return render_response(template_name, user=self.user)

def WhateverHandler(UserPageHandler):
    def get(self):
        return self.user_response('template_name.html')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜