当我使用Django的开发服务器时,以下代码在本地工作,但我在Nginx和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
我有时会在发布到第二个视图后收到KeyError。基于documentation on when sessions are saved,似乎应该保存会话变量,因为它直接修改会话。另外,如果我通过提供错误页面的调试面板并通过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 :(得分:0)
好的,我终于弄明白了这个问题。
默认情况下,当您使用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
我将settings.py中的SESSION_ENGINE更改为'django.contrib.sessions.backends.db',错误消失了。 https://docs.djangoproject.com/en/1.11/ref/settings/#session-engine
希望这对其他人有帮助!