您的位置:首页 > 其它

flask_login模块实现过程

2017-06-08 14:11 495 查看
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 equal
2、登录接口
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函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  login flask