Python Cronjob定期刷新django视图的缓存
我在为特定的django视图每小时重置缓存时遇到了一些问题 现在,我正在使用cache_页面装饰器使用Memcached缓存我的视图。但是缓存会在一段时间后过期,一些用户会取消缓存请求 @缓存页面(3600)Python Cronjob定期刷新django视图的缓存,python,django,cron,memcached,Python,Django,Cron,Memcached,我在为特定的django视图每小时重置缓存时遇到了一些问题 现在,我正在使用cache_页面装饰器使用Memcached缓存我的视图。但是缓存会在一段时间后过期,一些用户会取消缓存请求 @缓存页面(3600) 定义我的视图(请求): 如何编写自己的django manage.py命令,从cron每隔一小时刷新此视图的缓存 换句话说,我应该在这里的答案中提到的refresh_cache.py文件中添加什么内容: 谢谢 在你的应用程序中,你可以创建一个名为management的文件夹,其中包含另
定义我的视图(请求):
如何编写自己的django manage.py命令,从cron每隔一小时刷新此视图的缓存 换句话说,我应该在这里的答案中提到的refresh_cache.py文件中添加什么内容:
谢谢 在你的应用程序中,你可以创建一个名为
management
的文件夹,其中包含另一个文件夹commands
和一个空的\uuu init\uuuu.py
文件。在命令中
创建另一个\uuuu init\uuuuu.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作业中。您可以看看这一点,但基本上可以使用crontab-e编辑cron作业,使用crontab-l查看正在运行的cron作业
您可以在中找到所有这些以及更多内容。我想扩展Roberts的答案,以填写
#刷新缓存的代码
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)
谢谢你的回复,罗伯特。但是你能告诉我“刷新缓存的代码”里有什么吗。如何调用视图并使用cache.set()设置对缓存的响应您不调用视图。而是添加进行刷新的零件。这是因为视图可能正在执行您不希望在cron作业中执行的其他操作。至于细节,看看我是否想缓存我的整个视图(这是我的主页)?如何通过refresh.py中的handle函数将缓存设置为对整个视图的响应?文档似乎建议cache_页面不缓存整个视图,也就是说,缓存每个进程,而只缓存其输出。如果这是真的,则可以取消此输出调用.delete()。在缓存视图中添加前缀,并查看正在使用的键,以便准确地知道要删除的键。根据“删除缓存视图”命令,我不知道是否存在。嗯。。。这对你有帮助。实际上,有几种解决方案: