gpt4 book ai didi

python - Django 缺少 Vary :Cookie header for cached views

转载 作者:行者123 更新时间:2023-11-28 17:13:29 25 4
gpt4 key购买 nike

我有一个非常复杂的基于 Django 1.11 的网络应用程序。前一段时间,用户开始报告他们正在获取“其他人的 View ”——memcached 为他们提供了装饰器 @cache_page(xx) 缓存的 html,而不区分缓存宽限期内的 session 。

经过进一步调查,我发现在某些情况下 Vary: Cookie header 丢失并且提供了错误的“ session ”。奇怪的是,它仅在使用 curl 查询后端时显示(没有 session 、用户等 -> 后端服务登录在缓存 View 中)。

不幸的是,这个问题真的很难重现,有时会发生,有时不会。我什至从头开始构建一个简单的 Django 应用程序,看看我是否可以检查是什么原因。观察到的是,当删除 @cache_page 或添加 login_required 时,问题不会发生。

我最终从 View 中删除了所有@cache_page 装饰器,此后在生产中未观察到该问题,但这是一种解决方法,我想知道原因是什么。

如果任何人有任何提示可能是什么原因,将不胜感激!

最佳答案

您可能遇到了这个 open bug :

Since view decorators run on the outgoing response first, before response middleware, the cache_page decorator caches the response before any of the mentioned response middlewares have a chance to add their Vary headers. This means two things: 1) the cache key used won't include the headers the response ought to vary on, and Django may later serve that response to users who really shouldn't get it, and 2) when that cached response is later served to a user, it still won't include the Vary header that it should have, and thus may also be cached wrongly by an upstream HTTP cache.

换句话说,在缓存响应时 SessionMiddleware 还没有机会设置 Vary: Cookie header ,因此所有 session 都会共享相同的缓存键。

您可以通过显式指定 Vary header 来解决这个问题。例如:

from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie

@cache_page()
@vary_on_cookie()
def my_view():
pass

关于python - Django 缺少 Vary :Cookie header for cached views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45793163/

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