django-redis缓存

一.redis之django-redis

自定义连接池

view.py

import redis
from django.shortcuts import render,HttpResponse
from utils.redis_pool import POOL
 
def index(request):
    conn = redis.Redis(connection_pool=POOL)
    conn.hset('kkk','age',18)
 
    return HttpResponse('设置成功')
def order(request):
    conn = redis.Redis(connection_pool=POOL)
    conn.hget('kkk','age')
 
    return HttpResponse('获取成功')

通过第三方组件操作redis

安装

pip3 install django-redis

配置

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "密码",
        }
    }
}

使用

django中views.py

import redis
from django.shortcuts import render,HttpResponse
from django_redis import get_redis_connection
 
 
def index(request):
    conn = get_redis_connection("default")
    conn.hset("kkk","age",20)
    return HttpResponse('设置成功')
def order(request):
    conn = get_redis_connection("default")
    print(conn.gset("kkk","age"))
    return HttpResponse('获取成功')

drf中views.py

from rest_framework.views import APIView
from rest_framework.response import Response
 
from django.core.cache import cache
 
class OrderView(APIView):
    def get(self,request,*args,**kwargs):
        # conn = get_redis_connection('default')
        cache.set('a','b')
        print(cache.get('a'))
        return Response('..')

全站缓存

使用中间件,经过一系列的认证等操作,如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,
当返回给用户之前,判断缓存中是否已经存在,如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存

MIDDLEWARE = [
        'django.middleware.cache.UpdateCacheMiddleware',
        # 其他中间件...
        'django.middleware.cache.FetchFromCacheMiddleware',
    ]

一个放在最上面,一个放在最下面

views.py

from django.shortcuts import render,HttpResponse
import time
 
 
def index(request):
    ctime = str(time.time())
    return HttpResponse(ctime)
 
def order(request):
    ctime = str(time.time())
    return HttpResponse(ctime)

配置了全站缓存,在不同的时间(一定范围内),上面两个视图返回的时间是一样的,都是缓存时的时间

单独视图缓存

方式一:通过装饰器

from django.views.decorators.cache import cache_page
 
        @cache_page(60 * 15)
        def my_view(request):
            ...

方式二:通过url

from django.views.decorators.cache import cache_page
 
        urlpatterns = [
            url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),
        ]

局部页面缓存

1.引入TemplateTag

{% load cache %}

2.使用缓存

{% cache 5000 缓存的key %}
       缓存内容
{% endcache %}

posted @ 2023-02-26 16:21  MISF  阅读(213)  评论(0编辑  收藏  举报
     JS过度和变形效果演示   
  
    html5.png