You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask会话值在虚拟主机环境无法持久化的问题求助

Flask Session Persistence Issues in Python 2 CGI Environment

Let’s work through why your session data isn’t sticking between requests and fix it step by step:

1. Add a Secret Key (Non-Negotiable!)

Flask requires a secret key to sign session cookies—without it, the server can’t validate or persist session data across requests. You’re missing this critical line in your test code. Add it right after initializing your app:

app.secret_key = 'your-secure-random-secret-key'  # Use a long, random string for production

For Python 2, stick with a byte string or properly encoded Unicode string here to avoid compatibility hiccups.

2. Fix Flask-Session Storage for CGI

Your commented-out filesystem session config is on the right track, but mkdtemp() creates a temporary directory that gets cleaned up between CGI requests (since each request runs as a separate process). Instead, use a persistent directory you control:

import os
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_PERMANENT"] = False
# Create a dedicated session directory (ensure the web server can write to it)
session_dir = os.path.join('/home/user_name/public_html', 'flask_sessions')
if not os.path.exists(session_dir):
    os.makedirs(session_dir)
    # Lock down permissions so only the server can access the directory
    os.chmod(session_dir, 0o700)
app.config["SESSION_FILE_DIR"] = session_dir
Session(app)

This ensures session files are retained across requests instead of being deleted after each CGI process ends.

3. Fix CGI Environment Variables

CGI environments often lack critical variables needed for Flask to set and read cookies correctly. Add these lines to your CGI script (mas.cgi) before running CGIHandler().run(app):

# Ensure cookie-related environment variables are set
if 'HTTP_HOST' not in os.environ:
    os.environ['HTTP_HOST'] = 'your-domain.com'  # Replace with your actual domain
if 'SERVER_NAME' not in os.environ:
    os.environ['SERVER_NAME'] = 'your-domain.com'

Without these, Flask might generate cookies that your browser doesn’t send back in subsequent requests.

4. Use Python 2-Compatible Flask-Session Version

Newer Flask-Session versions dropped Python 2 support. Install a compatible release via pip:

pip install Flask-Session==0.3.2

This version works reliably with Python 2 and Flask’s legacy flask.ext.session import.

5. Debug Session Behavior

Add debug logs to track what’s happening with sessions across requests. Update your test routes:

@app.route('/set/')
def set():
    session['key'] = 'value'
    # Print session details to CGI error logs
    print "Session ID (set):", session.sid
    print "Session data:", session
    return 'ok'

@app.route('/get/')
def get():
    print "Received session cookie:", request.cookies.get('session')
    print "Session ID (get):", session.sid
    return "{}".format(session.get('key'))

Check your web server’s CGI error logs (usually in /var/log/apache2/ or your host’s control panel) to see if the session IDs match between /set/ and /get/ requests. If they don’t, the cookie isn’t being sent back correctly.

Final Updated Test Code

Here’s your test.py with all fixes applied:

import sys
import os
sys.path.insert(0, '/home/user_name/public_html')
from flask import Flask, request, session
from flask.ext.session import Session

app = Flask(__name__)
# Critical: Set secret key
app.secret_key = 'your-long-random-secret-key'

# Configure persistent filesystem sessions
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_PERMANENT"] = False
session_dir = os.path.join('/home/user_name/public_html', 'flask_sessions')
if not os.path.exists(session_dir):
    os.makedirs(session_dir)
    os.chmod(session_dir, 0o700)
app.config["SESSION_FILE_DIR"] = session_dir

Session(app)

@app.route('/set/')
def set():
    session['key'] = 'value'
    print "Session ID (set):", session.sid
    return 'ok'

@app.route('/get/')
def get():
    print "Received cookie:", request.cookies.get('session')
    print "Session ID (get):", session.sid
    return "{}".format(session.get('key'))

Additional Checks

  • File Permissions: Make sure the flask_sessions directory is writable by the web server user (e.g., www-data or your hosting account user). Run chown user_name:www-data flask_sessions if needed.
  • CGI Script Permissions: Ensure mas.cgi has execute permissions: chmod +x /home/user_name/public_html/cgi-bin/mas.cgi.
  • Flask Version: Use a Python 2-compatible Flask release like Flask==0.12.5 (newer versions dropped Python 2 support).

内容的提问来源于stack exchange,提问作者Mustaghees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:51:56