Flask-Login中装饰器@login_manager.user_loader的作用及原理
Flask-Login通过装饰器@login_required来检查访问视图函数的用户是否已登录,没有登录时会跳转到login_manager.login_view = 'auth.login'所注册的登录页。登录时即需调用login_user()函数,而在内部调用了由我们注册的回调函数。
Flask-Login就是通过装饰器,来注册回调函数,当没有sessionID时,通过装饰器指定的函数来读取用户到session中,达到在前端模板中调用当前登录用户current_user的目的,该装饰器就是:
@login_manager.user_loader
其功能类似如下
class Test():
# 在Test中并没有真正的定义callback
def feature(self):
self.callback() def decorate(self, func):
self.callback=func
return func test = Test() # 将fun注册为回调函数
@test.decorate
def fun():
print(1) # 调用feature将触发回调函数
test.feature() #
装饰器user_loader:
def user_loader(self, callback):
'''
This sets the callback for reloading a user from the session. The
function you set should take a user ID (a ``unicode``) and return a
user object, or ``None`` if the user does not exist. :param callback: The callback for retrieving a user object.
:type callback: callable
'''
self.user_callback = callback
return callback
这个装饰器的目的即将回调函数赋给self.user_callback
在login_user函数内部:
user_id = getattr(user, current_app.login_manager.id_attribute)()
session['user_id'] = user_id # 在这里设置用户id
session['_fresh'] = fresh
session['_id'] = current_app.login_manager._session_identifier_generator() if remember:
session['remember'] = 'set'
if duration is not None:
try:
# equal to timedelta.total_seconds() but works with Python 2.6
session['remember_seconds'] = (duration.microseconds +
(duration.seconds +
duration.days * 24 * 3600) *
10**6) / 10.0**6
except AttributeError:
raise Exception('duration must be a datetime.timedelta, '
'instead got: {0}'.format(duration)) _request_ctx_stack.top.user = user
user_logged_in.send(current_app._get_current_object(), user=_get_user())
调用时将user的属性写入session,并绑定到当前的请求上下文。由于HTTP是无状态的,每次发起新请求时flask会创建一个请求上下文,在分发路由时flask-login根据cookie判断用户并绑定到当前的请求上下文,由于这种绑定关系的存在,那么每次新的请求发生时都需要获取user看一下最后绑定的代码:
def reload_user(self, user=None):
ctx = _request_ctx_stack.top if user is None:
user_id = session.get('user_id')
if user_id is None:
ctx.user = self.anonymous_user()
else:
if self.user_callback is None:
raise Exception(
"No user_loader has been installed for this "
"LoginManager. Add one with the "
"'LoginManager.user_loader' decorator.")
user = self.user_callback(user_id)
if user is None:
ctx.user = self.anonymous_user()
else:
ctx.user = user
else:
ctx.user = user
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
self.user_callback就是装饰器装饰的回调函数load_user(),reload_user的作用就是当user无值时调用该方法获取user并绑定到当前的请求上下文,绑定的意义在于每次当我们使用current_user的时候,会直接从当前上下文中返回。
装饰器login_required:
def login_required(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if current_app.login_manager._login_disabled:
return func(*args, **kwargs)
elif not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
return func(*args, **kwargs)
return decorated_view
Flask-Login中装饰器@login_manager.user_loader的作用及原理的更多相关文章
- python flask route中装饰器的使用
问题:route中的装饰器为什么感觉和平时使用的不太一样,装饰器带参数和不太参数有什么区别?被修饰的函数带参数和不带参数有什么区别? 测试1:装饰器不带参数,被修饰的函数也不带参数. def log( ...
- 8.Python中装饰器是什么?
Python中装饰器是什么? A Python decorator is a specific change that we make in Python syntax to alter functi ...
- 第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法
第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法 上节介绍了Python中类的静态方法,本节将结合案例详细说明相关内容. 一. 案例说明 本节定义了类Sta ...
- flask --- 03 .特殊装饰器, CBV , redis ,三方组件
一.特殊装饰器(中间件) 1.before_request 在请求进入视图函数之前 @app.before_request def look(): 2. after_request 在结束视图函数之后 ...
- flask session,蓝图,装饰器,路由和对象配置
1.Flask 中的路由 *endpoint - url_for 反向地址 *endpoint 默认是视图函数名 *methods 指定视图函数的请求方式,默认GET defaults={& ...
- Flask系列06--(中间件)Flask的特殊装饰器 before_request,after_request, errorhandler
一.使用 Flask中的特殊装饰器(中间件)方法常用的有三个 @app.before_request # 在请求进入视图函数之前 @app.after_request # 在请求结束视图函数之后 响应 ...
- python中装饰器的执行细节
本文代码借用 廖雪峰的python教程(官网:http://www.liaoxuefeng.com/) 不了解装饰器的可以先看教程 直接上带参数装饰器的代码 def log(text): def de ...
- flask(1.1)装饰器装饰多个视图函数出现的问题
目录 1.装饰器装饰多个视图函数出现的问题 2.使用装饰器修复技术解决该问题 1.装饰器装饰多个视图函数出现的问题 代码实例: from flask import Flask, request, re ...
- Python类中装饰器classmethod,staticmethod,property,
@classmethod 有的时候在类中会有一种情况,就是这个方法并不需要使用每一个对象属性 因此 这个方法中的self参数一个完全无用的参数,使用classmethod class A: __cou ...
随机推荐
- Paper | Feedback Networks
目录 读后总结 动机 故事 ConvLSTM图像分类网络 损失函数 与Episodic Curriculum Learning的结合 实验方法 发表在2017年CVPR. 读后总结 这篇论文旨在说明: ...
- linux操作系统 - 综合习题
登录超级用户,完成以下操作: [linux@slave053 ~]$ su - 1.用户和组群管理(本大题共5小题,共10分) (1)创建两个用户tangseng,monkey,并指定密码为12345 ...
- Java网络传输数据加密算法
算法可逆,具有跨平台特性 import java.io.IOException; import java.io.UnsupportedEncodingException; import java.se ...
- NETCore下IConfiguration和IOptions的用法(转载)
原文:https://www.jianshu.com/p/b9416867e6e6 新建一个NETCore Web API项目,在Startup.cs里就会开始使用IConfiguration和IOp ...
- 响应国家号召 1+X 证书 Web 前端开发考试模拟题
1+x证书Web前端开发初级理论考试样题2019 http://blog.zh66.club/index.php/archives/149/ 1+x证书Web前端开发初级实操考试样题2019 http ...
- IDEA不能读取配置文件,springboot配置文件无效、IDEA resources文件夹指定
- 缘起 Dubbo ,讲讲 Spring XML Schema 扩展机制
背景 在 Dubbo 中,可以使用 XML 配置相关信息,也可以用来引入服务或者导出服务.配置完成,启动工程,Spring 会读取配置文件,生成注入 相关 Bean.那 Dubbo 如何实现自定义 X ...
- colmap编译过程中出现,无法解析的外部符号错误 “__cdecl google::base::CheckOpMessageBuilder::ForVar1(void)”
错误提示: >colmap.lib(matching.obj) : error LNK2019: 无法解析的外部符号 "__declspec(dllimport) public: cl ...
- 倒计时3天!i春秋四周年盛典狂欢,钜惠不停
六月注定是不平凡的 感恩父亲节 父爱如山亦如海 难忘毕业季 青春无悔不散场 嗨购618 优惠福利送不停 更值得期待的是 在这个不平凡的六月 迎来了i春秋四周年庆典 当周年庆遇到618 会擦出怎样的火花 ...
- 通过MES技术居然可以防止制造数据造假?
近些年来我们经历了太多制造数据造假事件,特别是前段时间曝出的医药制造事件更是将我们群众的愤怒值推到了最高点.不过我们最应当做的是,冷静下来,思考一下各行各业的我们是不是都该做些什么了?毕竟当下一个灾难 ...