auth模块 在程序运行开始进行验证等操作,
原理:在调用auth模块时,会先进行auth的构造方法,所以在init方法里面,就可以执行.
1,auth模块,
class Auth(object): def __init__(self, app=None): self.app = app # if app: self.init_app(app) def init_app(self, app): #传过来的app可以进行任何操作. app.auth_manager = self app.before_request(self.check_login) #调用flask的@before_request中间件装饰器,
app.context_processor(self.auth_context_processor)
#这里app.context_processor装饰self.auth_context_processor,并且返回到
上下文里,在之后可以直接调用current_user, PS:放到上下文里,是字典形式.
def auth_context_processor(self): name = session.get('user') return dict(current_user=name) def check_login(self): # print(request.url) # print(request.path) if request.path == '/login': return None if session.get('user'): return None return redirect('/login') def permission(self): pass def login(self,data): session['user'] = data
2,调用auth模块时,先实例化auth()
Auth(app),把需要的参数传过去,然后在里面进行操作.