How to delete Flask HTTP Sessions from the Database on session.clear()
<p>I implemented a server side Session in Flask with SQLAlchemy based on this <a href="http://flask.pocoo.org/snippets/110/" rel="nofollow">snippit</a>:</p>

<pre><code>class SqlAlchemySession(CallbackDict, SessionMixing):
    ...

class SqlAlchemySessionInterface(SessionInterface):
    def __init__(self, db):
        self.db = db

    def open_session(self, app, request):
        ...

    def save_session(self, app, session, response):
        ...
</code></pre>

<p>Everything works as expected. When the user logs in, a session is stored in the database, and the session id is placed in a cookie and returned to the user. When the user logs out, <code>session.clear()</code> is called, and the cookie is removed from the user.</p>

<p>However, the session is not deleted from the database. I was hoping that I could implement this logic in my <code>SqlAlchemySessionInterface</code> class, as opposed to defining a function and calling this instead of <code>session.clear()</code>.</p>

<p>Likewise, in the <a href="https://github.com/pallets/flask/blob/master/flask/sessions.py" rel="nofollow">sessions.py</a> code, there isn't any reference to <code>clear</code>, and the only time a cookie is deleted is <a href="https://github.com/pallets/flask/blob/master/flask/sessions.py" rel="nofollow">if the session was modified</a>.</p>

<p>The <a href="http://flask.pocoo.org/docs/0.11/api/#sessions" rel="nofollow">API documentation for sessions</a> also doesn't indicate how the <code>clear</code> method works.</p>

<p>Would anyone know of a way of accomplishing this, other than replacing all my calls to <code>session.clear()</code> with:</p>

<pre><code>def clear_session():
    sid = session.get('sid')
    if sid:
        db.session.query(DBSession).filter_by(sid=sid).delete()
        db.session.commit()
    session.clear()
</code></pre>

<p>If you want to remove duplication, you can define a function called <code>logout_user</code></p>

<p>In that function, you can remove the session record from your database as well as <code>session.clear()</code>.</p>

<p>Call this function when <code>\logout</code> or wherever suitable.</p>

python flask