Skip to content

Commit 3ad03f0

Browse files
committed
更新了第46天的内容
1 parent b74e0de commit 3ad03f0

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

Day41-55/06.中间件的应用.md

+41-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
```Python
66
def praise_or_criticize(request: HttpRequest):
77
"""投票"""
8-
if 'user' in request.session:
8+
if 'username' in request.session:
99
try:
1010
tno = int(request.GET.get('tno', '0'))
1111
teacher = Teacher.objects.get(no=tno)
@@ -93,3 +93,43 @@ MIDDLEWARE = [
9393

9494
### 自定义中间件
9595

96+
Django中的中间件有两种实现方式:基于类的实现方式和基于函数的实现方式,后者更接近于装饰器的写法。装饰器实际上是代理模式的应用,将横切关注功能(与正常业务逻辑没有必然联系的功能,例如:身份认证、日志记录、编码转换之类的功能)置于代理中,由代理对象来完成被代理对象的行为并添加额外的功能。中间件对用户请求和响应进行拦截过滤并增加额外的处理,在这一点上它跟装饰器是完全一致的,所以基于函数的写法来实现中间件就跟装饰器的写法几乎一模一样。下面我们用自定义的中间件来实现对用户进行登录验证的功能。
97+
98+
```Python
99+
"""
100+
middlewares.py
101+
"""
102+
from django.shortcuts import redirect
103+
104+
105+
def check_login_middleware(func):
106+
107+
def wrapper(request, *args, **kwargs):
108+
# 获取请求的资源路径
109+
path = request.path
110+
# 如果请求的资源路径在设定的元组中就表示需要登录验证
111+
if path in ('/vote/praise/', '/vote/criticize/'):
112+
if 'username' not in request.session:
113+
# session中没有username就重定向到登录页
114+
return redirect('login')
115+
return func(request, *args, **kwargs)
116+
117+
return wrapper
118+
```
119+
120+
修改配置文件,激活中间件使其生效。
121+
122+
```Python
123+
MIDDLEWARE = [
124+
'django.middleware.security.SecurityMiddleware',
125+
'django.contrib.sessions.middleware.SessionMiddleware',
126+
'django.middleware.common.CommonMiddleware',
127+
'django.middleware.csrf.CsrfViewMiddleware',
128+
'django.contrib.auth.middleware.AuthenticationMiddleware',
129+
'django.contrib.messages.middleware.MessageMiddleware',
130+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
131+
'debug_toolbar.middleware.DebugToolbarMiddleware',
132+
'vote.middlewares.check_login_middleware',
133+
]
134+
```
135+

0 commit comments

Comments
 (0)