2017-05-21 48 views
0

當我使用Django的開發服務器時,下面的代碼在本地工作,但我遇到了Nginx和Gunicorn生產中的間歇性錯誤。Django Session KeyError存在密鑰時

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 

我有時會張貼到所述第二視圖之後接收KeyError異常。根據documentation on when sessions are saved,似乎會話變量應該被保存,因爲它正在直接修改會話。另外,如果我走了會話ID提供的錯誤頁面的調試面板,並通過Django的API訪問會話,我可以看到「new_post」會話變量

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 

有我丟失的東西?在此先感謝您的幫助!

+0

這個變量由什麼組成? – Exprator

+0

new_post變量是我在字典理解中使用request.POST QueryDict創建的字典。這些值都是字符串。 – atm

+0

對不起,我錯過了new_mappings變量的名字?你確定它不是空白的?或者你錯過鍵入它代替new_post? – Exprator

回答

0

好吧,我終於明白了這個問題。

默認情況下,Django使用緩存中的會話,當您創建使用django-admin startproject project_name_here

在文檔它警告說,緩存只應在生產中如果使用Memcached的緩存後端,因爲本地內存中緩存後端不使用新項目多進程安全。 https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-cached-sessions

的文檔還告誡不要在部署清單本地內存緩存:https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/#caches

我改變了SESSION_ENGINE settings.py中爲「django.contrib.sessions.backends.db」和錯誤走了。 https://docs.djangoproject.com/en/1.11/ref/settings/#session-engine

希望這對別人有幫助!