I'm not finding any documentation for how to keep Django users logged in on Heroku using Redis and sessions.
Is it possible to reliably and securely persist sessions with Django on Heroku?
My guess is that the CSRF cookie and sessionid are not being set or correct in the response because Heroku Dynos are ephemeral resources.
Anyone know a fix? Should I try Memcached instead of Redis?
Heroku
Heroku Postgres
Hobby Basic
Heroku Redis
Hobby Dev
Hobby Dynos
Procfile
web: gunicorn appname.wsgi
worker: python manage.py runworker -v2
settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_SAVE_EVERY_REQUEST = True
# https://devcenter.heroku.com/articles/heroku-redis
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": os.environ.get('REDIS_URL'),
}
}
# ...
MIDDLEWARE_CLASSES = [
'django.middleware.cache.UpdateCacheMiddleware',
# ...
'django.middleware.cache.FetchFromCacheMiddleware',
]
# ...
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)
views.py
def logged_in(request):
if request.user.is_authenticated():
return render(request, "logged_in.html", {})
else:
return redirect('login')
# ...
@require_POST
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
request.session['logged_in'] = True
return redirect('logged_in')
# ...
The sessionid in the Response Cookie doesn't get set consistently which seems to be the issue.
Response Cookies
sessionid "" 0
from Django: Sessions not working on Heroku with Redis?
No comments:
Post a Comment