flask_login模块实现过程

发布时间:2020-06-28 13:36:37 作者:boy12626
来源:网络 阅读:1057

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模块实现过程

推荐阅读:
  1. 关于linux内核模块的装载过程
  2. Node中模块实现过程是怎么样的

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

login flask og

上一篇:java的值类型介绍

下一篇:java程序的错误类型可以分为几种

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》