Required login using decorator using gae python. p

2019-07-21 22:28发布

I'm trying to make a required login decorator using python gae.

import utils

def login_required(func):
    def check_login(self, *args, **kw):
        user_cookie = self.request.cookies.get("username")
        user_logged_in = False
        if user_cookie and utils.check_user_login("username"):
            username = user_cookie.split('|')[0]
            user_logged_in = True
            return func(self, *args, **kw)
        else:
            self.redirect('/login') 

    return check_login

class Handler(webapp2.RequestHandler):
    @login_required
    def render_with_login(self, template, template_values={}):
        self.render(template, template_values)

I'd like to pass the values to like username and user_logged_in in the decorator to the template. is that possible to do so? Is yes, how should I modify the code above? Thanks in advance.

1条回答
男人必须洒脱
2楼-- · 2019-07-21 22:39

I believe the issue you're having is with variable scope. user_logged_in and username are local to your check_login and gets executed before returning the new render_with_login function to be executed afterwards.

I think your best bet might be passing your username and user_logged_in as keyword args to your render_with_login function by changing:

    return func(self, *args, **kwargs)

to

    return func(self, username=username, user_logged_in=user_logged_in, *args, **kwargs)

I'm not a python expert by the way so I'm not positive about the scoping part, but it's my best guess. It would be easy to test anyways.

查看更多
登录 后发表回答