[Django学习] Django基础(13)_缓存

一. Django's cache framework

1. 内存缓存Memcached:

  Memcached作为一个守护进程运行,并分配一定数量的RAM。它所做的就是为在缓存中添加、检索和删除数据提供一个快速接口,所有数据都直接存储在内存中。基于内存的缓存有一个缺点:因为缓存的数据临时存储在内存中,所以如果服务器崩溃,数据将丢失。    

2. 数据库缓存DatabaseCache

  在数据库中创建一个缓存表,用于存储缓存的数据。    

3. 文件缓存

二. 内存缓存的设置与使用

(一)安装 python-memcached

(二)在settings.py中进行缓存设置

CACHES = {
    'default': {
        #选择内存缓存memcached.MemcachedCache
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

  其中,LOCATION格式为'ip:port'。ip是Memcached守护进程的ip地址,而port是Memcached运行的端口。

  Memcached的一个优秀特性是它能够在多个服务器上共享缓存。这意味着您可以在多台机器上运行Memcached守护进程,该程序将把这组机器当作单个缓存,而不需要在每台机器上重复缓存值。要利用这个特性,可以将服务器地址包含在位置中,或者作为分号或逗号分隔的字符串,或者作为列表。

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': [
            '172.19.26.240:11211',
            '172.19.26.242:11212',
            '172.19.26.244:11213',
        ]
    }
}

(三)引用并使用缓存

from django.core.cache import cache
from blogstatistics.utils import get_seven_days_read_data, get_blogs_hot_data

def home(request):
	ct = ContentType.objects.get_for_model(Blog)
	date_list,read_nums = get_seven_days_read_data(ct)

	# 获取7天热门数据缓存
	seven_hotdata_cache = cache.get('seven_hotdata_cache')
	if seven_hotdata_cache is None:
		seven_hotdata_cache = get_blogs_hot_data(7)
		cache.set('seven_hotdata_cache',seven_hotdata_cache,60)
		
	# 获取30天热门数据缓存
	thirty_hotdata_cache = cache.get('thirty_hotdata_cache')
	if thirty_hotdata_cache is None:
		thirty_hotdata_cache = get_blogs_hot_data(30)
		cache.set('thirty_hotdata_cache',thirty_hotdata_cache,60)

  其中,cache.get(缓存名Key)来获取缓存中特定Key的值;set(缓存名Key, 缓存值,留存时间(秒))。  

三. 数据库缓存的设置与使用

(一)在settings.py中进行缓存设置

CACHES = {
    'default': {
        # 以数据库缓存为例DatabaseCache
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        # 表名不可与其他名称相同
        'LOCATION': 'my_cache_table',
    }
}

(二)创建缓存表

python manage.py createcachetable

(三)引用并使用缓存

  同上

(四) 多个数据库中数据库缓存的使用

  如果在多个数据库中使用数据库缓存,还需要为数据库缓存表设置路由指令。例如,下面的路由器将把所有的缓存读操作都指向cache_copy,并将所有的写操作都写入cache_primary。缓存表将只同步到cache_primary上:

class CacheRouter:
    """A router to control all database cache operations"""

    def db_for_read(self, model, **hints):
        "All cache read operations go to the replica"
        if model._meta.app_label == 'django_cache':
            return 'cache_replica'
        return None

    def db_for_write(self, model, **hints):
        "All cache write operations go to primary"
        if model._meta.app_label == 'django_cache':
            return 'cache_primary'
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        "Only install the cache model on primary"
        if app_label == 'django_cache':
            return db == 'cache_primary'
        return None

  如果不为数据库缓存模型指定路由方向,则缓存后端将使用默认数据库。

四. 文件缓存的设置和使用

  基于文件的后端序列化并将每个缓存值存储为单独的文件。

(一)在settings.py中进行缓存设置

CACHES = {
    'default': {
        #选择文件缓存
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        #指定缓存文件存放路径
        'LOCATION': '/var/tmp/django_cache',
    }
}

注意:目录路径应该是绝对的。

     确保该设置所指向的目录是存在的,并且是由您的Web服务器运行的系统用户可读和写的。

(二)引用并使用缓存

  同上


 From: Django文档

猜你喜欢

转载自www.cnblogs.com/AngryZe/p/9355911.html