Home  >  Article  >  Database  >  Use of django-redis of redis

Use of django-redis of redis

尚
forward
2020-05-20 09:02:502593browse

Use of django-redis of redis

Customized connection pool

This method is the same as the normal py file operation redis, the code is as follows

views.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('获取成功')

Operation redis through third-party components

Installation

pip3 install django-redis

Configuration:

settings.py

# 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": "密码",
        }
    }
}

Use:

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")
    return HttpResponse('设置成功')
def order(request):
    conn = get_redis_connection("default")
    return HttpResponse('获取成功')
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('..')

Full site cache

Use middleware, after a series of authentication and other operations, if the content exists in the cache, use FetchFromCacheMiddleware Get the content and return it to the user.
Before returning it to the user, determine whether it already exists in the cache. If it does not exist, UpdateCacheMiddleware will save the cache to the cache, thereby realizing full-site caching

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

One placed At the top, the one at the bottom

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)

is configured with full-site caching. At different times (within a certain range), the time returned by the two views above is the same. , are all cache time

Individual view cache

Method one: through the decorator

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

Method two: through url

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

Partial page cache

1. Introduce TemplateTag

{% load cache %}

2. Use cache

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

For more redis knowledge, please pay attention toredis introductory tutorial column.

The above is the detailed content of Use of django-redis of redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete