2012-10-22 165 views
2

我试图重置我的缓存每小时一个特定的Django视图有一些麻烦。Cronjob定期刷新Django视图缓存

现在,我使用cache_page修饰器来缓存我的视图使用Memcached。但缓存在一段时间后过期,并且某些用户未缓存该请求。

@cache_page(3600)
高清my_view(请求):
...

我怎样写我自己的Django的manage.py命令来更新我的缓存对这一观点从cron每隔一小时?

换句话说,什么我把这里的答复中提到我的refresh_cache.py文件: Django caching - can it be done pre-emptively?

谢谢!

回答

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找到所有这些和更多。

+0

感谢您的回复Robert。但是,请您告诉我“#code刷新缓存”的含义。如何调用视图并使用cache.set()设置对缓存的响应 – Kiran

+0

您不调用该视图。相反,您添加了进行刷新的部分。这是因为该视图可能正在做一些你不想在cron工作中做的事情。至于具体细节,请参阅https://docs.djangoproject.com/en/dev/topics/cache/?from=olddocs#the-low-level-cache-api –

+0

如果我想缓存我的整个视图(这是我的主页)?如何将refresh缓存设置为refresh.py中句柄函数的整个视图的响应? – Kiran

1

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

Timezome +地理位置使缓存多少很难用,在我来说,我只是禁止他们的工作,也是我不知道如何使用的测试方法应用程序代码,但它似乎很好地工作。

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)