flask_login模块实现过程-创新互联
1、先创建用户表,该表继承flask_login 模块的UserMixin类

vi model.py

其中id字段是必须要有的,登录成功之后,每次请求界面,UserMixin类定义的获取该登录用户id的字段就是id
class UserMixin(object):
'''
This provides default implementations for the methods that Flask-Login
expects user objects to have.
'''
if not PY2: # pragma: no cover
# Python 3 implicitly set __hash__ to None if we override __eq__
# We set it back to its default implementation
__hash__ = object.__hash__
@property
def is_active(self):
return True
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
try:
print '99222', self.id
return text_type(self.id)
except AttributeError:
raise NotImplementedError('No `id` attribute - override `get_id`')
def __eq__(self, other):
'''
Checks the equality of two `UserMixin` objects using `get_id`.
'''
if isinstance(other, UserMixin):
return self.get_id() == other.get_id()
return NotImplemented
def __ne__(self, other):
'''
Checks the inequality of two `UserMixin` objects using `get_id`.
'''
equal = self.__eq__(other)
if equal is NotImplemented:
return NotImplemented
return not equal2、登录接口
vi views.py

前端验证成功后,通过login_user()函数记录登录状态

该过程会将user_id,及前端请求header存入session
3、添加回调函数
根据user_id获取用户对象
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
user_loader会将load_user函数复于LoginManager()类的self.user_callback属性

4、为其他函数加上@login_required装饰器

当用户访问index时,会判断该用户的登录状态,会通过reload_user属性重新加载用户

self.user_callback此时等于步骤3中的reload_user函数

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
新闻标题:flask_login模块实现过程-创新互联
URL链接:http://jxruijie.cn/article/essgi.html
