django中使用redis

第一种

安装redis模块
1.1在app中定义一个redis的连接池的py文件
import redis
POOL=redis.ConnectionPool(host='127.0.0.1',port=6379,max_connections=1000)
1.2函数视图
from django.shortcuts import render,HttpResponse
# Create your views here.
from app01.conn_pool import POOL
import redis
# 第一种从外面导入连接池

def set_redis(request):
    conn = redis.Redis(connection_pool=POOL)
    conn.set('slogan','天行健君子以自强不息1')
    return HttpResponse('设置成功')



def get_redis(request):
    conn = redis.Redis(connection_pool=POOL)
    slogan = conn.get('slogan').decode('utf-8')
    return HttpResponse(slogan)

第二种

使用django中自带的
from django_redis import get_redis_connection

# 第二种用django中自带的
def set_redis(request):
    conn = get_redis_connection()
    conn.set('name','zjh')
    return HttpResponse('设置成功')

def get_redis(request):
    conn = get_redis_connection()
    name = conn.get('name').decode('utf-8')
    return HttpResponse(name)

 

在settings中配置参数
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": 1000}
            # "PASSWORD": "123",
        }
    }
}

django中将页面缓存放入redis中(简单应用)

from django.views.decorators.cache import cache_page

@cache_page(10)
def get_time(request):
    import time
    ctime = time.time()
    return HttpResponse(ctime)

 

posted @ 2018-12-26 16:26  zhaijihai  阅读(2166)  评论(0编辑  收藏  举报