Tornado 判断用户登录状态和操作权限(装饰器)
判断是否登录:
def authenticated(method): '''''' @functools.wraps(method) def wrapper(self, *args, **kwargs): '''''' if not self.current_user: raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
判断是否有操作权限
def with_permission(permission): '''''' def _decorator(method): '''''' @functools.wraps(method) def wrapper(self, *args, **kwargs): '''''' user = self.current_user # 这里判断用户是否存在(登录) if not user: self.set_status(404) return if permission in user.permission_list: # 判断用户是否有足够的权限 method(self, *args, **kwargs) else: data = {"error": "need permission:%s" % permission} self.write_json(data, status=403) return wrapper return _decorator
此处可将两个装饰起结合用。也可用判断权限的装饰起,因为后者已经判断是否登录了
用法:
@ decorator.authenticated @ with_permission(permission.dashboard_manage) def delete(self, dashboard_id): '''''' dashboard = bil.get_dashboard(dashboard_id) if not dashboard: self.write_json('bad arguments', status=403) return dashboard.delete() self.write_json(dashboard.to_dict())
更多内容,可访问:http://rexyan.cn