当前位置: 首页 > 工具软件 > redis_admin > 使用案例 >

Django 框架中配置并连接 Redis

范翰飞
2023-12-01

1. 终端安装django-redis模块

关于django-redis的使用,参见文档:django-redis 中文文档 — Django-Redis 4.7.0 文档

pip install django-redis

2. 在配置文件中为会用到缓存的模块进行相关配置

# 设置redis缓存,假设redis没有设置密码;注意,项目上线时,需要调整路径
CACHES = {
    # 默认缓存, 房子0号库
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://@127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },

    # 提供给admin站点的session存储,放在1号库
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://@127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    
    # 提供存储短信验证码,放在2号库
    "sms_code":{
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://@127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }

}


# 设置用户登录admin站点时,记录登录状态的session保存到redis缓存中
SESSION_ENGINE = "django.contrib.sessions.backends.cache"

# 设置session保存的位置对应的缓存配置项
SESSION_CACHE_ALIAS = "session"

3. 通过django_redis操作redis数据库

参考:Welcome to redis-py’s documentation! — redis-py dev documentation

# 通过调用方法get_redis_connection传递对应的配置项名称,链接到redis数据库,获取redis对象
from django_redis import get_redis_connection
redis_conn = get_redis_connection("default")

4. 测试案例

4.1 视图代码

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from django_redis import get_redis_connection

# Create your views here.
class HomeAPIView(APIView):
    def get(self,request):
        """测试接口"""
        print("hello")

        # 直接操作redis
        redis = get_redis_connection("session")
        # lrange brother 0 -1
        brother = redis.lrange("brother", 0, -1)
        print(brother)

        return Response(brother, status.HTTP_200_OK)

4.2 创建和注册子应用home

# 终端下输入:
cd pconeapi/apps
python ../../manage.py startapp home
# settings/dev.py中配置导包路径

# 当前项目的主应用开发目录
BASE_DIR = Path(__file__).resolve().parent.parent

sys.path.insert(0, str( BASE_DIR / "apps") )
# print(sys.path)


DEBUG = True

ALLOWED_HOSTS = ["*"]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'home',
]

4.3 注册路由

# 主应用目录下 pconeapi/urls.py注册子路由
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', include("home.urls")),
]
# 子应用目录下子路由home/urls.py

from django.urls import path
from . import views
urlpatterns = [
    path("demo/", views.HomeAPIView.as_view()),
]

 类似资料: