官方查閱資料:https://django-redis-chs.readthedocs.io/zh_CN/latest/python
1.安裝django-redis擴展包redis
$ pip install django-redis
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:數據庫
session:django
SESSION_ENGINE後端
session存儲機制
使用Redis保存。SESSION_CACHE_ALIAS:session
session數據
。配置完成後:運行程序,測試結果。app
後端調用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')