一、安装包
pip3 install redis
二、调用模块
from redis import *
sr = StrictRedis(host=‘localhost‘, port=6379, db=0)
sr = StrictRedis() # 简写
三、使用StrictRedis对象操作string类型
from redis import *
if __name__ == ‘__main__‘:
try:
sr = StrictRedis()
# 添加一个key为name,value为hao
res = sr.set(‘name‘, ‘hao‘) # res为bool,添加是否成功
except Exception as e:
print(e)
四、使用redis存储session
pip3 install django-redis-sessions
- 修改django项目settings文件,增加如下选项
# 设置redis存储session信息
SESSION_ENGINE = ‘redis_session.session‘
# redis服务的ip地址
SESSION_REDIS_HOST = ‘localhost‘
# 端口
SESSION_REDIS_PORT = 6379
# redis对应数据库
SESSION_REDIS_DB = 2
SESSION_REDIS_PASSWORD = ‘‘
SESSION_REDIS_PREFIX = ‘session‘
redis数据库与python交互