在我的 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/