Skip to content

zhenzi0322/Django-stores-sessions-in-redis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Django-stores-sessions-in-redis

第一种配置方法

官网地扯:django-redis

安装模块

pip install django-redis

settings.py文件

增加如下配置信息:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",  # 指明使用redis的1号数据库
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/3",  # 指明使用redis的3号数据库
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

# session使用的存储方式
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# 指明使用哪一个库保存session数据
SESSION_CACHE_ALIAS = "session"

第二种配置方法

官网地扯:django-redis-sessions

安装模块

pip install django-redis-sessions

settings文件

SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS = {
    'host': '127.0.0.1',
    'port': 6379,
    'db': 1, # 指明使用1号数据库
    'password': '',
    'prefix': 'session',
    'socket_timeout': 1
}

用法

配置路由

from django.urls import path

from . import views

urlpatterns = [
    path("set_session/",views.set_session,name="set_session"),
    path("get_session/",views.get_session,name="get_session"),
]

配置视图

from django.shortcuts import render, HttpResponse

# Create your views here.

def set_session(request):
    # 设置session
    request.session['username'] = 'long'
    request.session['password'] = '123456'
    return HttpResponse("设置成功")


def get_session(request):
    # 获取session
    username = request.session.get('username')
    password = request.session.get('password')
    text = 'username=%s, password=%s' % (username, password)
    return HttpResponse(text)

地扯栏访问

http://127.0.0.1:8000/set_session/,效果图如下:

http://127.0.0.1:8000/get_session/,效果图如下:

最后进入redis客户端中查看

第一种配置方法的截图

第二种配置方法的截图

About

django把session存储到redis中

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages