Cronjob定期刷新django视图的缓存

时间:2012-10-22 19:19:43

标签: python django cron memcached

我尝试在特定的django视图中每小时重置一次缓存时遇到了一些麻烦。

现在,我正在使用cache_page装饰器使用Memcached缓存我的视图。但缓存会在一段时间后过期,并且某些用户会解除请求。

@cache_page(3600)
def my_view(request):
     ...

如何编写自己的django manage.py命令,每小时从cron刷新一次此视图的缓存?

换句话说,我在回答中提到的refresh_cache.py文件中放了什么: Django caching - can it be done pre-emptively?

谢谢!

2 个答案:

答案 0 :(得分:2)

在您的应用中,您可以创建一个名为management的文件夹,其中包含另一个文件夹commands和一个空的__init__.py文件。在commands内,您可以创建另一个__init__.py和一个用于编写自定义命令的文件。我们称之为refresh.py

# refresh.py

from django.core.management.base import BaseCommand, CommandError
from main.models import * # You may want to import your models in order to use  
                          # them in your cron job.

class Command(BaseCommand):
    help = 'Posts popular threads'

    def handle(self, *args, **options):
    # Code to refresh cache

现在您可以将此文件添加到您的cron作业中。您可以查看此tutorial,但基本上您使用crontab -e编辑cron作业和crontab -l以查看正在运行的cron作业。

您可以在Django documentation中找到所有这些以及更多内容。

答案 1 :(得分:1)

我想扩展罗伯茨的答案以填写# Code to refresh cache

Timezome + location让缓存很难处理,在我的情况下我只是禁用它们,我也不确定在应用程序代码中使用测试方法,但它似乎运行良好。

from django.core.management.base import BaseCommand, CommandError
from django.test.client import RequestFactory
from django.conf import settings

from ladder.models import Season
from ladder.views import season as season_view


class Command(BaseCommand):
    help = 'Refreshes cached pages'

    def handle(self, *args, **options):
        """
        Script that calls all season pages to refresh the cache on them if it has expired.

        Any time/date settings create postfixes on the caching key, for now the solution is to disable them.
        """

        if settings.USE_I18N:
            raise CommandError('USE_I18N in settings must be disabled.')

        if settings.USE_L10N:
            raise CommandError('USE_L10N in settings must be disabled.')

        if settings.USE_TZ:
            raise CommandError('USE_TZ in settings must be disabled.')

        self.factory = RequestFactory()
        seasons = Season.objects.all()
        for season in seasons:
            path = '/' + season.end_date.year.__str__() + '/round/' + season.season_round.__str__() + '/'
            # use the request factory to generate the correct url for the cache hash
            request = self.factory.get(path)

            season_view(request, season.end_date.year, season.season_round)
            self.stdout.write('Successfully refreshed: %s' % path)