gpt4 book ai didi

python - django 中 MIDDLEWARE_CLASSES 的顺序

转载 作者:行者123 更新时间:2023-11-28 18:52:38 25 4
gpt4 key购买 nike

djangobook 有这个 section

To activate this CSRF protection, add 'django.contrib.csrf.middleware.CsrfMiddleware' to the MIDDLEWARE_CLASSES setting in your settings file. This middleware needs to process the response after SessionMiddleware, so CsrfMiddleware must appear before SessionMiddleware in the list (because the response middleware is processed last-to-first).

然而,djangoproject page告诉它不同

MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', )

这有点令人困惑..CsrfViewMiddleware 现在是否在 SessionMiddleware 之后处理响应?有人可以澄清一下吗?

最佳答案

来自 Django 文档:

Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)

来源:https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#how-csrf-works

这是我在新生成的 Django 项目 (1.3.1) 中的中间件列表:

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

所以,是的,Django 现在在 session 中间件之后处理 CSRF 中间件。

The Django Book 已经严重过时了——这些天我不会用它作为学习 Django 的资源。另一方面,Django 教程是一个很好的资源。

关于python - django 中 MIDDLEWARE_CLASSES 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9935876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com