redis数据库

首先了解下我们为什么要用redis,redis可以用于我们页面的缓存,打个比方加入很多用户在请求我们的网页,那么我们的服务器是不是就要不断的进行数据库的查询这样会给我们服务器带来性能影响,那么我们把查询到的数据写到缓存里这样我们就可以不用查库直接展示缓存中的内容即可,这样很有效的降低了服务器的压力。

首先要安装redis数据库

下载链接:https://pan.baidu.com/s/1Q29h7-jbaHIPPxvZ1jiIjg   提取码:mxqn   

安装时会让我们给定数据库大小一般用于缓存的话50Mb就足够了
 

安装完成后安装redis就要安装跟python进行连接的库了:

这里有两个库

pip install redis              跟python关联库

pip install django-redis  基于上个库关联Django库

然后在Django项目内设置settings文件 之后就可以使用了

#配置缓存系统
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache", # 指定缓存使用的引擎
        "LOCATION": "redis://127.0.0.1:6379",   # 写在内存中的变量的唯一值 缓存数据保住在那
        'TIMEOUT':300,             # 缓存超时时间(默认为300秒,None表示永不过期)
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

首先是局部缓存

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect
#导入类视图 
from django.views import View
#导入数据库类
from myapp.models import Student
#导入缓存库
from django.core.cache import cache

#定义一个视图类
class CachTest(View):

    #定义方法
    def get(self,request):

        '''
        这里只是使用了cache方法如果想使用要先去判断有没有如果没有在去复制,若不用多行注释内方法会没有效果原因是一直在从新赋值

        #判断缓存内是否有数据
        val = cache.get('stu_1','no')
        #如果缓存内没有就读取数据库
        if val == 'no':
            cache.get('stu_1')
            #读取数据
            res_one = Student.objects.filter(id=2)
            #设置缓存
            cache.set('stu_1','值',60)
            val = cache.get('stu_1','no')
        
        '''


        #给内存中存入key为key1的键值  
        cache.set('key1','你好')

        #通过key来获取之前存储的值
        val = cache.get('key1')

        #通过设置超时时间,来让变量自动消亡
        # cache.set('key2','hello',20)

        val2 = cache.get('key2','该变量已经超时')

        # ttl方法,用来判断变量的生命周期 0表示无此键值或者已过期 None表示未设置时间

        #删除key
        cache.delete('key2')

        # print(cache.ttl('key2'))
        # print(val2)
        print(cache.get('mailcode','未获取到'))

        return HttpResponse('这里是缓存测试')

全视图缓存(视图方法)

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect
#导入页面缓存类
from django.views.decorators.cache import cache_page
#导入数据库类
from myapp.models import Student

#定义方法视图 设定缓存为60秒刷新一次
@cache_page(60)
def page_cache(request):
    
    #读取数据库
    res = Student.objects.all()

    return render(request,'pagecache.html',locals())

全视图缓存(类视图方法)

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect
#导入页面缓存类
from django.views.decorators.cache import cache_page
#导入数据库类
from myapp.models import Student
#导入类装饰器
from django.utils.decorators import method_decorator


#定义页面试图类  设置60秒刷新  指定作用于get请求视图方法加
@method_decorator(cache_page(60),name='get')
class PageCache(View):
    #定义方法
    def get(self,request):
        
        #读取数据库
        res = Student.objects.all()
        
        return render(request,'pagecache.html',locals())
原文地址:https://www.cnblogs.com/Niuxingyu/p/10557706.html