2012-10-22 120 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)