python - Django: session 在 Heroku 上没有按预期工作

标签 python django session cookies redis

在我的 Heroku 上的 Django 应用程序中,用户不断注销并且 session 没有持续存在。用户可以登录,但他们会随机注销——即使在 /admin/ 站点也是如此。

我的 Django/Heroku 配置有什么问题吗?

目前在标准 Dynos 上运行 Django 1.11.16。

settings.py

SECRET_KEY = os.environ.get("SECRET_KEY", "".join(random.choice(string.printable) for i in range(40)))

SESSION_COOKIE_DOMAIN = ".appname.com"
CSRF_COOKIE_DOMAIN = ".appname.com"

SECURE_SSL_REDIRECT = True

# ...

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.csrf',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# ...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'appname',
    }
}

# https://devcenter.heroku.com/articles/python-concurrency-and-database-connections
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

最佳答案

问题是 SECRET_KEY 在 Heroku 上不是静态的。 SECRET_KEY 更改会中断 session 。解决方法是向 Heroku 配置添加静态 SECRET_KEY:

heroku config:set SECRET_KEY=`openssl rand -base64 32`

关于python - Django: session 在 Heroku 上没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52535488/

相关文章:

spring - 如何制作无状态的 Web 应用程序?特别是对于 Spring MVC?

asp.net - session 在 4 分钟内过期

python - Pandas 读取没有标题或索引的数据

python - 从 Excel 中原子读取(用于 luigi 工作流程)

django - 多语言 django 网站上的搜索功能

python - 值错误 : No JSON object could be decoded - Django request. 正文

php - 即使我正在工作, session 也会过期, session 生命周期,Ajax 和 Symfony2

Python:使用 PIL 制作动画

python - 自动简化冗余算术关系

python - 如何找到 pg_config 路径