django中使用redis存储session

1.安装django-redis-sessions模块

 

2.django中settings.py配置

SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS = {
    'host': '10.0.0.200',
    'port': 6379,
    'db': 1,
    'password': '',
    'prefix': 'session',
    'socket_timeout': 1
}

3.编写视图函数views.py

def set_session(request):
    request.session['username'] = 'soulchild'
    return HttpResponse('设置session')


def get_session(request):
    res = request.session.get('username')
    return HttpResponse(res)

4.配置路由urls.py

    url(r'^set_session$', views.set_session, name='set_session'),
    url(r'^get_session$', views.get_session, name='get_session'),

 

5.验证

启动django

python manage.py runserver

打开:http://127.0.0.1:8000/set_session

查看redis

 

打开:http://127.0.0.1:8000/get_session

结果正常显示

 

# 关于哨兵模式和集群可参考:

https://pypi.org/project/django-redis-sessions/

相关文章

发表新评论