【python-django后端开发】Redis缓存配置使用详细教程!!!

官方查阅资料:https://django-redis-chs.readthedocs.io/zh_CN/latest/

1. 安装django-redis扩展包

1.安装django-redis扩展包

$ pip install django-redis

  

2. 配置Redis数据库 setting.py

CACHES = {
    "default": { # 默认
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": { # session
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
},
"code": { # 验证码
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "session"

  

default:

  • 默认的Redis配置项,采用0号Redis库。

session:

  • 状态保持的Redis配置项,采用1号Redis库。

SESSION_ENGINE

  • 修改session存储机制使用Redis保存。

SESSION_CACHE_ALIAS:

  • 使用名为"session"的Redis配置项存储session数据

配置完成后:运行程序,测试结果。

后端调用Redis示例

from django_redis import get_redis_connection
from apps.verifications import constants
from libs.captcha.captcha import captcha
from django import http

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')

  

多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。
原文地址:https://www.cnblogs.com/LiuXinyu12378/p/11242186.html