https://pythonav.com/wiki/detail/10/82/
5. django連接redis
按理說搞定上一步python代碼操作redis之后,在django中應用只需要把上面的代碼寫到django就可以了。
例如:django的視圖函數中操作redis
import redisfrom django.shortcuts import HttpResponse# 創建redis連接池POOL = redis.ConnectionPool(host='10.211.55.28', port=6379, password='foobared', encoding='utf-8', max_connections=1000)def index(request):# 去連接池中獲取一個連接conn = redis.Redis(connection_pool=POOL)conn.set('name', "武沛齊", ex=10)value = conn.get('name')print(value)return HttpResponse("ok")
上述可以實現在django中操作redis。但是,這種形式有點非主流,因為在django中一般不這么干,而是用另一種更加簡便的的方式。
第一步:安裝django-redis模塊(內部依賴redis模塊)
pip3 install django-redis
第二步:在django項目的settings.py中添加相關配置
# 上面是django項目settings中的其他配置....CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://10.211.55.28:6379", # 安裝redis的主機的 IP 和 端口"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient","CONNECTION_POOL_KWARGS": {"max_connections": 1000,"encoding": 'utf-8'},"PASSWORD": "foobared" # redis密碼}}}
第三步:在django的視圖中操作redis
from django.shortcuts import HttpResponsefrom django_redis import get_redis_connectiondef index(request):# 去連接池中獲取一個連接conn = get_redis_connection("default")conn.set('nickname', "武沛齊", ex=10)value = conn.get('nickname')print(value)return HttpResponse("OK")
