【问题标题】:Django Session KeyError when key exists密钥存在时的Django Session KeyError
【发布时间】:2017-10-21 00:19:40
【问题描述】:

当我使用 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,似乎应该保存会话变量,因为它是直接修改会话。另外,如果我使用提供错误页面的调试面板的 sessionid 并通过 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

我有什么遗漏吗?提前感谢您的帮助!

【问题讨论】:

  • 这个变量由什么组成?
  • new_post 变量是我在字典理解中使用 request.POST QueryDict 创建的字典。值都是字符串。
  • 对不起,我错过了 new_mappings 变量的名称?你确定它不是空白的吗?或者你错过了用它来代替 new_post?

标签: django python-3.x redirect post session-variables


【解决方案1】:

好的,我终于找到了问题所在。

默认情况下,当您使用 django-admin startproject project_name_here 创建新项目时,Django 使用缓存会话

在文档中它警告说,如果使用 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

希望这对其他人有帮助!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 2013-10-17
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多