使用装饰器使用gae python的必需登录。传递参数? [英] Required login using decorator using gae python. passing parameters?

查看:110
本文介绍了使用装饰器使用gae python的必需登录。传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import utils 

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

返回check_login

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

我想将这些值传递给装饰器中的用户名和user_logged_in到模板中。是否有可能这样做?是的,我应该如何修改上面的代码?提前致谢。

解决方案

我相信你遇到的问题是可变范围。 user_logged_in和username是你本地的check_login,并在返回之后执行新的render_with_login函数之前得到执行。



我认为你最好的选择可能是传递你的用户名和user_logged_in作为关键字通过改变你的render_with_login函数的参数:
$ b $ pre $ return $ func(self,* args,** kwargs)

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

我不是一个蟒蛇专家,所以我对于范围部分并不积极,但这是我最好的猜测。无论如何,这很容易测试。


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.

解决方案

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.

这篇关于使用装饰器使用gae python的必需登录。传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆