python使用装饰器实现登录判断

本文共有1729个字,关键词:

问题:python中想将登录判断封装成一个方法,就不用每次都重写一遍了

解决:python提供装饰器功能,使用装饰器可以很简单的实现

方法:

def login_required(user_type="any"):
    """
        Decorate methods with this to require that the user be logged in.
    """ 
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            if not self.current_user:
                if self.request.method in ("GET", "HEAD"):
                    self.redirect("/login?r=%s" % urllib.quote(self.request.path))
                    return raise tornado.web.HTTPError(403)
                if user_type == "admin":
                    type_byte = 2
                else:
                    type_byte = 1
                if not self.current_user.type & type_byte:
                    self.write("无相应权限查看本页内容")
                    return
                return method(self, *args, **kwargs)
            return wrapper
        return decorator

上面的方法包括了权限判断,可以省去,最简单的如下:

def login_required():
    """
        Decorate methods with this to require that the user be logged in.
    """
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            if not self.current_user:
                if self.request.method in ("GET", "HEAD"):
                    self.redirect("/login")
                    return raise tornado.web.HTTPError(403)
                return method(self, *args, **kwargs)
            return wrapper
        return decorator

使用时只要在所需的方法上面加上:@login_required()就可以了

版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论