Django视图缓存:如何设置过期时间?

问题描述 投票:0回答:1

我想缓存一些视图直到月底。

例如

@cache_page_expire_at_end_of_month
def some_view(request):
   ...

我发现了这个老问题Django 每个视图缓存:设置过期时间而不是缓存超时? 但我无法让它工作。

python django caching python-decorators
1个回答
0
投票

要将 Django 视图缓存到月底,您需要创建一个自定义装饰器来计算到当前月底为止的剩余时间,然后使用具有特定超时值的 Django 缓存机制。 Django 没有内置的装饰器来将缓存过期设置为月底,因此您必须自己实现此功能。

以下是有关如何操作的分步指南:

  1. 计算到月底的时间
  2. 创建自定义装饰器
  3. 将自定义装饰器应用于视图

从 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
        ...
© www.soinside.com 2019 - 2024. All rights reserved.