美文网首页
Flask-session中的cookie操作

Flask-session中的cookie操作

作者: yiludege | 来源:发表于2017-03-18 20:28 被阅读1905次

    flask-session中默认的cookie操作有:提取cookie和设置cookie

    提取cookie:

        def open_session(self, app, request):
            s = self.get_signing_serializer(app)
            if s is None:
                return None
            val = request.cookies.get(app.session_cookie_name)
            if not val:
                return self.session_class()
            max_age = total_seconds(app.permanent_session_lifetime)
            try:
                data = s.loads(val, max_age=max_age)
                return self.session_class(data)
            except BadSignature:
                return self.session_class()
    

    Flask默认的提取机制只会取得一个cookie即session_cookie_name,如果session.permanent设置为true,之后permanent_session_lifetime才能呢发挥作用,max_age才能有值。只有采用我们的secret-key并且在max_age范围内的cookie才能够成功的loads出来。

    设置cookie:

        def save_session(self, app, session, response):
            domain = self.get_cookie_domain(app)
            path = self.get_cookie_path(app)
    
            # Delete case.  If there is no session we bail early.
            # If the session was modified to be empty we remove the
            # whole cookie.return self.session_interface.save_session(self, session, response)
            if not session:
                if session.modified:
                    response.delete_cookie(app.session_cookie_name,
                                           domain=domain, path=path)
                return
    
            # Modification case.  There are upsides and downsides to
            # emitting a set-cookie header each request.  The behavior
            # is controlled by the :meth:`should_set_cookie` method
            # which performs a quick check to figure out if the cookie
            # should be set or not.  This is controlled by the
            # SESSION_REFRESH_EACH_REQUEST config flag as well as
            # the permanent flag on the session itself.
            if not self.should_set_cookie(app, session):
                return
    
            httponly = self.get_cookie_httponly(app)
            secure = self.get_cookie_secure(app)
            expires = self.get_expiration_time(app, session)
            val = self.get_signing_serializer(app).dumps(dict(session))
            response.set_cookie(app.session_cookie_name, val,
                                expires=expires, httponly=httponly,
                                domain=domain, path=path, secure=secure)
    

    值得注意的是val = self.get_signing_serializer(app).dumps(dict(session))采用secret-key时间戳签名的方式加密整个session的。
    expires = self.get_expiration_time(app, session)只有在session.permanent设置为true的时候才会添加datetime.utcnow()+permanent_session_lifetime到expires中去的。

    总结

    flask的session对cookie的处理采用两套时间保证机制,expires的设置保证了浏览器保存cookie的时间,而secret-key+时间戳再次保证了cookie的时间正确性。

    相关文章

      网友评论

          本文标题:Flask-session中的cookie操作

          本文链接:https://www.haomeiwen.com/subject/vtrpnttx.html