安装 django-redis

  1. pip install django-redis==4.11.0 -i https://pypi.tuna.tsinghua.edu.cn/simple

配置

  1. # settings.py
  2. CACHES = {
  3. "default": {
  4. "BACKEND": "django_redis.cache.RedisCache",
  5. "LOCATION": "redis://127.0.0.1:6379",
  6. "OPTIONS": {
  7. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  8. "CONNECTION_POOL_KWARGS": {"max_connections": 100}
  9. # "PASSWORD": "密码",
  10. }

使用

  1. # 在哪里使用,就在那里调用
  2. # views.py
  3. from django_redis import get_redis_connection
  4. conn = get_redis_connection()
  5. conn.set(phone, random_code, ex=30) # 将手机号、随机短信码存入,并设置过期时间为30s