- 项目结构 demo中的url配置
from django.urls import path,include
urlpatterns = [
path(r'sess/', include('sess.urls'))
]
- sess中url配置
1 from django.urls import path
2 from sess import views
3
4
5 urlpatterns = [
6 path('index/', views.index),
7 path('info/', views.info),
8 path('delete/session/', views.delete_session),
9 path('login/', views.login)
10 ]
- sess-views中实现了未登录跳转至登录页面,登录后跳转至首页功能,
delete_session,清除数据
-
session的操作
- 添加session:request.session['name'] = 'zhangsan'
- 获取session中的值: request.session.get('name')
- 删除一条key-value: del request.session['name']
- 删除全部内容: request.session.clear()
- 删除在存储中session记录: request.session.flush()
1 import datetime
2
3 from django.http import HttpResponse, JsonResponse
4 from django.shortcuts import redirect
5 from django.shortcuts import render
6
7
8 def index(request):
9 print(type(request.session))
10 #设置session
11 #request.session['username'] = 'chen'
12 #设置过期时间
13 #request.session.set_expiry(30)
14 # 返回Json字符串
15 return HttpResponse('首页')
16
17
18 def login(request):
19 if request.method == 'GET':
20 # 渲染页面
21 return render(request, 'login.html')
22 else:
23 # post请求,说明要提交登录的数据
24 username = request.POST.get('username')
25 password = request.POST.get('password')
26 # 登录成功
27 # 在session中记录用户信息
28 request.session['username'] = username
29 request.session['password'] = password
30 return redirect('/sess/index/')
31
32
33 #登录之后才可访问页面
34 def info(request):
35 # 先判断是否登录
36 # 如果登录了那么可以正常访问.
37 # 如果没登录, 就跳转到登录页面.
38 username = request.session.get('username')
39 if username:
40 # 登录成功, 正常显示页面
41 return HttpResponse(f"hell {username}")
42 else:
43 # 没登录, 跳转去登录页面
44 return redirect('/sess/login/')
45
46 def delete_session(request):
47 #单独删除key的session
48 #del request.session['username']
49 #request.session.clear()
50 request.session.flush()
51 return HttpResponse('deleting success')
- 连接redis做30秒缓存数据-30秒后刷新数据清除
- django本身没有实现存储session到redis的功能, 需要借助第三方的包django-redis
- pip install django-redis==4.10.0 -i https://pypi.douban.com/simple
- demo中需填写下redis配置
-
1 STATIC_URL = '/static/' 2 3 CACHES = { 4 "default": { 5 "BACKEND": "django_redis.cache.RedisCache", 6 "LOCATION": "redis://127.0.0.1:6379/1", 7 "OPTIONS": { 8 "CLIENT_CLASS": "django_redis.client.DefaultClient", 9 } 10 } 11 } 12 SESSION_ENGINE = "django.contrib.sessions.backends.cache"
-