Reputation: 27
I am experiencing an issue with session persistence in a Flask application. The application works fine on my local machine, but on the server, the session data (user_id) is lost between requests. Logs on Local (Works as Expected):
2025-01-05 01:26:38 - INFO - Session before token handling: {'_permanent': True}
2025-01-05 01:26:39 - INFO - Dataset saved for user 5.
2025-01-05 01:26:39 - INFO - Token processed successfully for user 5.
2025-01-05 01:26:39 - INFO - Session at the start of chat: {'_permanent': True, 'user_id': '5'}
Logs on Server (Session Data Missing):
2025-01-05 01:28:52 - INFO - Session before token handling: {'_permanent': True}
2025-01-05 01:28:53 - INFO - Dataset saved for user 5.
2025-01-05 01:28:53 - INFO - Token processed successfully for user 5.
2025-01-05 01:28:53 - INFO - Session at the start of chat: {'_permanent': True}
2025-01-05 01:28:53 - WARNING - User not logged in. Using default dataset.
As seen in the logs, the user_id is set in the session during the token handling route but is missing in the subsequent request to the chat route.
Here is the relevant Flask setup and session configuration:
from flask import Flask, session
from flask_session import Session
import os
from datetime import timedelta
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Session configuration
app.config["SESSION_TYPE"] = "filesystem"
SESSION_FILE_DIR = "./flask_session"
if not os.path.exists(SESSION_FILE_DIR):
os.makedirs(SESSION_FILE_DIR)
app.config["SESSION_FILE_DIR"] = SESSION_FILE_DIR
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=30)
app.config["SESSION_USE_SIGNER"] = True
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = False # Using HTTP for now
Session(app)
Session data is being set in the following route:
@app.route("/<path:token>", methods=["GET"])
def handle_token(token):
session["user_id"] = "5" # Example user_id
return "Token processed successfully"
And read in the chat route:
@app.route("/", methods=["GET"])
def chat():
user_id = session.get("user_id")
if not user_id:
return "User not logged in. Using default dataset.", 400
return f"User logged in with ID: {user_id}"
Environment Details
Local Environment:
OS: macOS/Linux
Flask Version: 2.x
Python Version: 3.9.x
Server Environment:
OS: Ubuntu 20.04
Deployed via Gunicorn behind Nginx
Flask Version: 2.x
Python Version: 3.9.x
What I’ve Tried
**Potential Hypotheses
Questions
Additional Notes
Upvotes: 0
Views: 32