Flask - Save session data in database like using c

2019-01-25 22:32发布

I am creating a web app using Flask.

I wonder if it is possible to save user session data like

session['ishappy'] = true

in database like it's done in Django using SessionMiddleware where you have options to choose between cookies and database.

And if it is what should I import to my Flask app.

3条回答
甜甜的少女心
2楼-- · 2019-01-25 22:47

You should check out Flask-KVSession, which is self-described as

a drop-in replacement for Flask‘s signed cookie-based session management. Instead of storing data on the client, only a securely generated ID is stored on the client, while the actual session data resides on the server.

Which basically describes traditional server-side sessions. Note that it supports multiple database backends:

Flask-KVSession uses the simplekv package for storing session data on a variety of backends.

See the Example Use for an example of what to import and how to configure it.

查看更多
来,给爷笑一个
3楼-- · 2019-01-25 23:02

One of colleagues recently posted the post, which explains how to work and share the user sessions. Hope that helps:

查看更多
再贱就再见
4楼-- · 2019-01-25 23:04

I suggest you implement your own Session and SessionInterface by subclassing flask defaults. Basically, you need to define your own session class and a session interface class.

class MyDatabaseSession(CallbackDict, SessionMixin):

    def __init__(self, initial=None, sid=None):
        CallbackDict.__init__(self, initial)
        self.sid = sid
        self.modified = False

The above class will now have a session id (sid) that will be stored in the cookie. All the data related to this session id will be stored in your mysql database. For that, you need to implement the following class and methods below:

class MyDatabaseSessionInterface(SessionInterface):

    def __init__(self, db):
        # this could be your mysql database or sqlalchemy db object
        self.db = db

    def open_session(self, app, request):
        # query your cookie for the session id
        sid = request.cookies.get(app.session_cookie_name)

        if sid:
            # Now you query the session data in your database
            # finally you will return a MyDatabaseSession object

    def save_session(self, app, session, response):
        # save the sesion data if exists in db
        # return a response cookie with details
        response.set_cookie(....) 

Also, you can define a model for storing session data:

class SessionData(db.Model):
    def __init__(self,sid,data):
        self.sid = sid
        self.data = data
        # and so on...

The following snippets should give you an idea:

http://flask.pocoo.org/snippets/75/

http://flask.pocoo.org/snippets/86/

http://flask.pocoo.org/snippets/110/

查看更多
登录 后发表回答