开发者

Cleaner way to get user name in pylons with repoze.name

in mako template, i use this

${request.environ['repoze.who.identity']['user']}

and the render in controller:

render('file.html')

can i write this better without passing i开发者_如何学Pythonn parameter everytime?


Well, you can auto add the varible in the base controller in /lib/base.py. This will add it to every controller in your pylons application automatically. I'm using repoze.what and what I do is in base.py I put:

# if there's no user set, just setup a blank instance
c.current_user = auth.get_user(User()) 

And that's just a convienence function I wrote into an auth lib. User() is a blank instance of the User model so that the template has something and won't throw a invalid key error.

def get_user(default):
    """Return the user object from the `repoze.who` Metadata Plugin

    :param default: default item to send back if user not logged in

    Since we might not be logged in and template choke on trying to output
    None/empty data we can pass in a blank User object to get back as a default
    and the templates should work ok with default empty values on that

    """
    if 'repoze.who.identity' in request.environ:
        return request.environ['repoze.who.identity']['user']
    else:
        return default
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜