Python3 Django 框架中使用脚本预缓存多计算页面

前面几篇文章我们讲述了

由于我们的数据里已达到百万计,而且页面中有比较多的mysql跨库跨表的计算,在打开页面时会造成时间过长。所以我们需要在Django框架中如何对页面进行预缓存数据。

本来我们打算使用 request 页面请求的方式,但是项目中需要登录以后才能看到这个页面,所以这条路不考虑。

但是我们可以将预缓存的数据提前计算好放在Django的缓存中,然后在使用时显示出来。

注:可以使用文件缓存的方式进行,然后看定期是否自动有新文件生成出来

代码实例

#!/usr/bin/env python
# coding: utf-8

######
#  调用方法  python .\manage.py flushCaches
######

from django.core.cache import cache
from scheduling.views import getIndexResult
import time , datetime , hashlib
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    def handle(self, *args, **options):
        date =  time.strftime("%Y-%m-%d %H:%M")
        print('开始预缓存首页数据,时间:%s'%date)
        cache_key = hashlib.md5(('index_'+date).encode(encoding='UTF-8')).hexdigest()
        if not cache.get(cache_key) :
            cache.get_or_set(cache_key, getIndexResult(date) ,60*60)

调用方法

python .\manage.py flushCaches

crontab设置

*/1 * * * * cd /data/wwwroot/scheduling/web/ ; /usr/bin/python manage.py flushCaches >> /tmp/flushCache.log 2>&1

下次我们打开页面时,速度就很快了。

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注