當我使用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
有我丟失的東西?在此先感謝您的幫助!
這個變量由什麼組成? – Exprator
new_post變量是我在字典理解中使用request.POST QueryDict創建的字典。這些值都是字符串。 – atm
對不起,我錯過了new_mappings變量的名字?你確定它不是空白的?或者你錯過鍵入它代替new_post? – Exprator