分别设置每个会话的生存时间KVsession烧瓶

时间:2018-11-05 15:27:36

标签: flask flask-kvsession

KBsession根据PERMANENT_SESSION_LIFETIME存储会话TTL,有一种方法可以覆盖特定会话

编辑: 因此,我有两种不同的登录API,我需要给其中一个用户的任何用户登录一个无限的会话TTL,另一个用户将使用PERMANENT_SESSION_LIFETIME值 注意:KBsession后端是Redis

1 个答案:

答案 0 :(得分:0)

我认为最好的方法是使用Session Interface创建特定的处理。这只是一个例子,但我希望您能理解方法。

from flask import Flask, session as flask_session, jsonify

flask_app = Flask(__name__)
# just a few user types
UNIQUE_USER_TYPE = 'unique'
DEFAULT_USER_TYPE = 'default'

@flask_app.route('/login-default')
def login_default():
    flask_session['user_type'] = DEFAULT_USER_TYPE
    return 'login default done'

@flask_app.route('/login-unique')
def login_unique():
    flask_session['user_type'] = UNIQUE_USER_TYPE
    return 'login unique done'

@flask_app.route('/session-state')
def get_session_state():
    return jsonify(dict(flask_session))


class UserTypeSessionInterface(SecureCookieSessionInterface):

    def get_expiration_time(self, app, session):
        """
        I just override method. Just demonstration.
        It's called from save_session() and open_session()
        """
        if session.get('user_type') == UNIQUE_USER_TYPE:
            # set 1 hour for unique users
            delta = datetime.utcnow() + timedelta(hours=1)
        else:
            # set 3 hour for default users
            delta = datetime.utcnow() + timedelta(hours=3)
        # add datetime data into session
        session['lifetime'] = delta.strftime('%Y-%m-%dT%H:%M:%S')
        return delta
# use our custom session implementation
flask_app.session_interface = UserTypeSessionInterface()

现在运行服务器,打开新的专用窗口/login-default/session-state

# default behaviour
{
  "lifetime": "2018-11-06T16:22:21", 
  "user_type": "default"
}

再打开一个私人窗口/login-unique/session-state

# unique behaviour
{
   "lifetime": "2018-11-06T14:25:17", 
   "user_type": "unique"
}

因此,会话存储工具并不重要(redis,cassandra或其他)。您只需要实现open_session()save_session()

class YourSessionProcessor(SessionInterface):

    def open_session(self, app, request):
        # just do here all what you need
        pass

    def save_session(self, app, session, response):
        # just do here all what you need
        pass

flask_app.session_interface = YourSessionProcessor()

您还可以使用自定义会话类(仅作为示例):

from flask.sessions import SessionMixin
from werkzeug.datastructures import CallbackDict

class CustomSession(CallbackDict, SessionMixin):

    def __init__(self, initial=None, sid=None):
        def on_update(self):
            self.modified = True

        CallbackDict.__init__(self, initial, on_update=on_update)
        self.sid = sid
        self.modified = False

# YourSessionProcessor
def open_session(self, app, request):
    # you can find any useful data in request
    # you can find all settings in app.config
    sid = request.cookies.get(app.session_cookie_name)
    # ... do here everything what you need
    return CustomSession(sid=sid)

希望这会有所帮助。