I'm using Flask-Session with Redis as the session store in my Flask application. However, I'm facing an issue where the session data is not persisting between requests. Here's the relevant code:
app = Flask(__name__)
CORS(app, supports_credentials=True)
r = redis.from_url("redis://localhost:6379")
r.ping()
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_USE_SIGNER"] = True
app.config["SESSION_REDIS"] = r
app.config["SECRET_KEY"] = "secret!" # TODO: change this to something more secure
app.save_session = True
app.logger.setLevel(logging.INFO)
socketio = SocketIO(
app,
async_mode="eventlet",
cors_allowed_origins="*",
manage_session=False,
)
Session(app)
@app.route("/")
def index():
print(f"Current working directory in main route: {os.getcwd()}")
if "user_id" not in session:
session["user_id"] = str(uuid.uuid4())
session.modified = True
user_id = session.get("user_id")
app.logger.info(user_id )
return render_template("index.html")
@socketio.on("user_input")
def handle_user_input(input_data):
app.logger.info("Debug: session['user_id'] in handle_user_input:", session.get("user_id"))
app.logger.info("User input received")
socketio.emit("received", {})
# Start processing the input
user_id = session.get("user_id")
app.logger.info(f"User id: {user_id}")
socketio.start_background_task(process_input, input_data, user_id)
app.logger.info("Started background task")
The issue is, in the block on user input the session is not the same as in the index() function, there is no values in it. 1. Thank you in advance for your help!
I have already checked the following:
The Redis server is running on localhost:6379, and I can successfully establish a connection to it. The flask_session package is installed. The necessary modules (Flask, session, render_template, flask_session, redis, uuid, logging) are imported in my code. The Flask-Session extension is initialized properly with the correct configuration. I also tried setting those, as seen in other posts about this issue: app.config["SAME_SITE"] = "None" app.config["SESSION_COOKIE_SECURE"] = True
Despite these checks, the session data is not persisting between requests. I would appreciate any guidance on what might be causing this issue and how to resolve it.