第一步 黑屏终端安装 三方包
> pip install django-redis-sessions
第二步 配置settings.py
# SESSION_ENGINE = 'redis_sessions.session' # SESSION_REDIS_HOST = '127.0.0.1' # SESSION_REDIS_PORT = 6379 # SESSION_REDIS_DB = 0 # SESSION_REDIS_PASSWORD = 'qwe123' # SESSION_REDIS_PREFIX = 'session'#这段配置用不了,使用下面的配置
SESSION_ENGINE = 'redis_sessions.session' SESSION_REDIS = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': '', 'prefix': 'session', 'socket_timeout': 1 }
最后 验证使用
view 配置:
def main(request): username=request.session.get('name','游客') return render(request,'myApp/main.html',{'username':username}) def login(request): return render(request, 'myApp/login.html') def showmain(request): username=request.POST.get('username') request.session['name']=username return redirect(main) def quit(request): logout(request) return redirect(main)
urls配置 path('main/', views.main), path('login/', views.login), path('showmain/', views.showmain), path('quit/', views.quit),
两个模板配置
main.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我的</title> </head> <body> <h1>欢迎:{{ username }}</h1> <a href="/login/">登陆</a> <a href="/quit/">注销</a> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action="/showmain/" method="post"> <input type="text" name="username"> <input type="submit" value="登录"> </form> </body> </html>