gpt4 book ai didi

django - 如果内容在缓存 TTL 到期之前发生更改,则更新缓存

转载 作者:IT王子 更新时间:2023-10-29 06:09:42 24 4
gpt4 key购买 nike

我正在使用 redis用于在 django 应用程序中缓存。我也在使用 Django Rest Framework ,这是我的问题。

我正在使用这样的缓存系统:

from django.views.decorators.cache import cache_page

urlpatterns = [
...
url(r'^some_url/$', cache_page(CACHE_TTL)(SomeView.as_view())
...
]

这里,SomeView是一个继承自APIView的类.

现在假设我们向这个 url 发出请求,我们收到一个 json 对象,其中包含这个 url 返回的任何一个实例。

然后我们继续删除(使用 django 的管理界面)该对象,并再次发出请求。预期的结果是一个空的 json 对象,但我收到的是同一个对象,没有变化,如果添加了一个新对象,也会发生同样的情况,响应仍然只有一个对象。

一段时间后(缓存中请求的 TTL)结果正确。

那么,我如何告诉 Django 缓存条目不再有效?

最佳答案

来自 Django’s cache framework :

There are a few other ways to control cache parameters. For example, HTTP allows applications to do the following:

  • Define the maximum time a page should be cached.

  • Specify whether a cache should always check for newer versions, only delivering the cached content when there are no changes. (Some caches might deliver cached content even if the server page changed, simply because the cache copy isn’t yet expired.)

In Django, use the cache_control view decorator to specify these cache parameters. In this example, cache_control tells caches to revalidate the cache on every access and to store cached versions for, at most, 3,600 seconds:

from django.views.decorators.cache import cache_control

@cache_control(must_revalidate=True, max_age=3600)
def my_view(request):
# ...

如果您正在缓存的页面经常变化并且您希望立即呈现这些更改(并且您缓存不会自动检测或检查更改)而不等待缓存 TTL,请使用 cache_control

关于django - 如果内容在缓存 TTL 到期之前发生更改,则更新缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384808/

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