flask_login模块实现过程
admin
2023-07-29 20:00:07
0

1、先创建用户表,该表继承flask_login 模块的UserMixin类

vi model.py

  flask_login模块实现过程

其中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

   flask_login模块实现过程

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

flask_login模块实现过程

该过程会将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属性

flask_login模块实现过程

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

flask_login模块实现过程

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

flask_login模块实现过程

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


flask_login模块实现过程

相关内容

热门资讯

伊朗情报部:捣毁4个与美以有关... 据伊朗法尔斯通讯社7月4日报道,伊朗情报部发表声明称,伊朗安全部门近日捣毁4个与美国和以色列情报机构...
佩洛西86岁丈夫被控肇事逃逸,... 当地时间7月3日傍晚,美国众议院南希·佩洛西的丈夫保罗,再一次因为驾车事故而遭到了指控。据报道称,保...
当着中方的面,菲律宾许下三点承... 难得很难得,菲律宾又向中国郑重承诺了。承诺什么?感觉承诺了至少三点。看新闻稿,2026年6月30日,...
首个世界杯8强产生!摩洛哥3-... 新华社美国休斯敦7月4日电(记者吴俊宽、赵建通)4日在美国休斯敦进行的美加墨世界杯首场16强赛中,摩...
瑞典最新涉华表态:钦佩、赞赏! 当地时间2026年7月4日,瑞典首相克里斯特松在斯德哥尔摩会见中共中央政治局委员、外交部长王毅。克里...
特朗普:内塔尼亚胡知道“谁是老... 新华社耶路撒冷7月4日电(记者庞昕熠 冯国芮)以色列总理办公室4日晚发表声明称,以总理内塔尼亚胡此前...
辽宁抚顺出现特大暴雨,致3人死... 新华社沈阳7月4日电(记者邹明仲)记者4日从辽宁省抚顺市防汛抗旱指挥部获悉,7月4日凌晨1时至7时许...
泽连斯基与特朗普通话,商定在北... △资料图当地时间4日,乌克兰总统泽连斯基在社交媒体发文表示,他于美国独立日当天同美国总统特朗普通话。...
内塔尼亚胡将访美与特朗普会晤 △内塔尼亚胡(左)与特朗普(右)(资料图)当地时间7月4日,美国总统特朗普在接受电话采访时表示,以色...