Django 视图缓存:如何设置过期时间?
我想把一些视图缓存到月底。
比如说:
@cache_page_expire_at_end_of_month
def some_view(request):
...
我发现了这个旧问题 Django每个视图的缓存:设置过期时间而不是缓存超时?,但是我试了之后没能成功。
1 个回答
1
要让Django的视图缓存到本月底,你需要自己写一个装饰器,这个装饰器会计算到本月底还有多少时间,然后利用Django的缓存机制来设置这个特定的过期时间。Django并没有现成的装饰器可以直接设置缓存到月底,所以你得自己实现这个功能。
下面是一步一步的指南,教你怎么做:
- 计算到月底的时间
- 创建自定义装饰器
- 把自定义装饰器应用到视图上
从django.utils.decorators导入method_decorator
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from datetime import datetime, timedelta
import calendar
def cache_page_expire_at_end_of_month(timeout_default=86400):
def decorator(view_func):
def _wrapped_view_func(*args, **kwargs):
# Calculate the current time and find the last day of the month
now = datetime.now()
_, last_day = calendar.monthrange(now.year, now.month)
end_of_month = datetime(now.year, now.month, last_day, 23, 59, 59)
# Calculate remaining seconds until the end of the month
delta = end_of_month - now
timeout = max(delta.total_seconds(), timeout_default)
# Apply the cache_page decorator with the calculated timeout
return cache_page(timeout)(view_func)(*args, **kwargs)
return _wrapped_view_func
return decorator
# Usage example
@cache_page_expire_at_end_of_month()
def some_view(request):
# Your view logic here
...
要把这个装饰器应用到基于类的视图上,你需要像这样使用method_decorator:
from django.utils.decorators import method_decorator
@method_decorator(cache_page_expire_at_end_of_month(), name='dispatch')
class SomeClassBasedView(View):
def get(self, request, *args, **kwargs):
# Your view logic here
...