classFlask(object): @setupmethod defbefore_request(self, f): """Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ self.before_request_funcs.setdefault(None, []).append(f)
defpreprocess_request(self): bp = _request_ctx_stack.top.request.blueprint # 从字典中获取所有被@flask_app.before_request注册的函数 # 键是None的表示应用注册的,此外还有蓝图的 funcs = self.before_request_funcs.get(None, ()) if bp isnotNoneand bp in self.before_request_funcs: funcs = chain(funcs, self.before_request_funcs[bp]) # 获取所有函数遍历执行,谁return了,就直接返回到客户端,所以这里要注意 for func in funcs: rv = func() if rv isnotNone: return rv