Search code examples
python-3.xflasksession

Is it possible to delete session outside Flask app?


I have two apps which are both launched by Flask. app1 is port 5000 and app2 is port 5001.

In my session, I have a key called username. I can delete session in app1 by hitting http://localhost:5000/delete_session

from flask import Flask

app1 = Flask(__name__)

@app1.get('/delete_session')
def delete_session():
    print(session.keys())  # print is: dict_keys(['username'])
    if "username" in session.keys():
        session.pop("username")
    return "Session clear"

@app1.post('/delete_session')
def delete_session_by_post():
    print(session.keys())  # print is empty: dict_keys([])
    if "username" in session.keys():
        session.pop("username")
    return "Session clear"

However, when I hit http://localhost:5001/logout, the session is not deleted. Because the session app1 get is empty dict_keys([])

import requests
from flask import Flask

app2 = Flask(__name__)

@app2.get('/logout')
def logout():
    requests.post(url='http://localhost:5000/delete_session')

Anyone knows why? Thanks in advance.


Solution

  • As long as they are on the same domain, they should be able to share cookies.

    The problem is that inside your app2 you are making a request to your app1 using requests which is a different client from the one that made a request to your app2/app1, so it doesn't store the same cookie.

    One simple way to solve this would be to instead redirect the client to your app1.

    from flask import Flask, redirect
    
    app2 = Flask(__name__)
    
    
    @app2.get("/logout")
    def logout():
        redirect("http://localhost:5000/delete_session")
    

    Another way, would be to import the function from app1 into your app2 and call it

    from flask import Flask, redirect
    from my_app import delete_session
    app2 = Flask(__name__)
    
    
    @app2.get("/logout")
    def logout():
        delete_session()
    

    Another way, would be to store sessions server side, for example a database, so you could read sessions and delete them from there.