安裝依賴
1
|
|
使用的三種方式
直接使用
1
2
|
import redis r = redis.Redis(host = '127.0.0.1' , port = 6379 , db = 1 , password = None , decode_responses = True ) |
連接池使用
1
2
3
|
import redis pool = redis.ConnectionPool(host = '127.0.0.1' , port = 6379 , db = 1 , max_connections = 100 , password = None , decode_responses = True ) r = redis.Redis(connection_pool = pool) |
緩存使用:要額外安裝 django-redis
安裝django-redis
1
|
pip install django-redis |
1.將緩存存儲位置配置到redis中:settings.py
1
2
3
4
5
6
7
8
9
10
11
12
|
CACHES = { "default" : { "BACKEND" : "django_redis.cache.RedisCache" , "LOCATION" : "redis://127.0.0.1:6379/0" , "OPTIONS" : { "CLIENT_CLASS" : "django_redis.client.DefaultClient" , "CONNECTION_POOL_KWARGS" : { "max_connections" : 100 }, "DECODE_RESPONSES" : True , "PSAAWORD" : "", } } } |
2.操作cache模塊直接操作緩存:views.py
1
2
3
4
5
|
from django.core.cache import cache # 結合配置文件實現插拔式 # 存放token,可以直接設置過期時間 cache. set ( 'token' , 'header.payload.signature' , 300 ) # 取出token token = cache.get( 'token' ) |
以上就是python中操作redis數據庫的三種方法的詳細內容,更多關于python中操作redis的資料請關注服務器之家其它相關文章!
原文鏈接:https://cloud.tencent.com/developer/article/1582311