资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

flask_login模块实现过程-创新互联

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

10年积累的成都网站设计、成都网站建设、外贸网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有北屯免费网站建设让你可以放心的选择与我们合作。

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

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


网站名称:flask_login模块实现过程-创新互联
网址分享:http://cdkjz.cn/article/essgi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220