Django Session KeyError when key exists

时光总嘲笑我的痴心妄想 提交于 2021-01-27 13:23:22

问题


The following code works locally when I use Django's development server, but I am running into intermittent bugs in production with Nginx and Gunicorn.

views.py

def first_view(request):
    if request.method == "POST":
        # not using a django form in the template, so need to parse the request POST
        # create a dictionary with only strings as values
        new_post = {key:val for key,val in request.POST.items() if key != 'csrfmiddlewaretoken'}
        request.session['new_post'] = new_mappings # save for use within next view

        # more logic here (nothing involving views)
        return redirect('second_view')

def second_view(request):
    if request.method == 'POST':
        new_post = request.session['new_post']
        # ... more code below
        # render template with form that will eventually post to this view

I will sometimes receive a KeyError after posting to the second view. Based on the documentation on when sessions are saved, it seems like the session variable should be saved since it is modifying the session directly. Also, if I take the sessionid provided the error page's debug panel and access the session via Django's API, I can see the 'new_post' session variable

python manage.py shell
>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='sessionid_from_debug_panel')
>>> s['new_post']
# dictionary with expected post items

Is there something I'm missing? Thanks in advance for your help!


回答1:


Ok, I finally figured out the issue.

By default Django uses cached sessions when you create a new project using django-admin startproject project_name_here

In the documentation it warns that caching should only be used in production if using the Memcached cache backend since the local-memory cache backend is NOT multi-process safe. https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-cached-sessions

The documentation also cautions against local memory caching in the deployment checklist: https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/#caches

I changed the SESSION_ENGINE in settings.py to 'django.contrib.sessions.backends.db' and the error went away. https://docs.djangoproject.com/en/1.11/ref/settings/#session-engine

Hope this is helpful to someone else!



来源:https://stackoverflow.com/questions/44094269/django-session-keyerror-when-key-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!