key 存在时出现 Django Session KeyError

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

当我使用 Django 的开发服务器时,以下代码在本地运行,但我在使用 Nginx 和 Gunicorn 的生产环境中遇到间歇性错误。

View .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

我有时会在发布到第二个 View 后收到 KeyError。基于documentation on when sessions are saved ,似乎应该保存 session 变量,因为它直接修改 session 。此外,如果我使用错误页面调试面板提供的 session ID 并通过 Django 的 API 访问 session ,我可以看到“new_post” session 变量

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

有什么我想念的吗?预先感谢您的帮助!

最佳答案

好吧,我终于想通了这个问题。

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

在文档中警告说,如果使用 Memcached 缓存后端,则只能在生产中使用缓存,因为本地内存缓存后端不是多进程安全的。 https://docs.djangoproject.com/en/1.11/topics/http/sessions/#using-cached-sessions

文档还在部署 list 中警告不要使用本地内存缓存: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

希望这对其他人有帮助!

关于 key 存在时出现 Django Session KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094269/

相关文章:

python - 实时动态更新 django 模板

javascript - 存储浏览器选项卡特定数据

apache - mod_rewrite 还是 mod_alias?

apache - 从 Apache VirtualHost 将 HTTPS 永久重定向到 HTTP

python - 从 MYSQL 读取模型时出现 DjangoUnicodeDecodeError

python - 在 Django 中使用过滤器获取最新记录

python - PyQt5.5 和 Qt5 许可证问题

Python Dropbox API v2 : error when passing SharedLinkSettings

python - 如何使用 scapy 模块发送请求并接受三个答案?

Grails 2.0 重定向包括应用程序上下文,即使我将其设置为 "/"