Skip to content

Commit

Permalink
更新了第46天的内容
Browse files Browse the repository at this point in the history
  • Loading branch information
jackfrued committed Jun 2, 2019
1 parent b74e0de commit 3ad03f0
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion Day41-55/06.中间件的应用.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
```Python
def praise_or_criticize(request: HttpRequest):
"""投票"""
if 'user' in request.session:
if 'username' in request.session:
try:
tno = int(request.GET.get('tno', '0'))
teacher = Teacher.objects.get(no=tno)
Expand Down Expand Up @@ -93,3 +93,43 @@ MIDDLEWARE = [

### 自定义中间件

Django中的中间件有两种实现方式:基于类的实现方式和基于函数的实现方式,后者更接近于装饰器的写法。装饰器实际上是代理模式的应用,将横切关注功能(与正常业务逻辑没有必然联系的功能,例如:身份认证、日志记录、编码转换之类的功能)置于代理中,由代理对象来完成被代理对象的行为并添加额外的功能。中间件对用户请求和响应进行拦截过滤并增加额外的处理,在这一点上它跟装饰器是完全一致的,所以基于函数的写法来实现中间件就跟装饰器的写法几乎一模一样。下面我们用自定义的中间件来实现对用户进行登录验证的功能。

```Python
"""
middlewares.py
"""
from django.shortcuts import redirect


def check_login_middleware(func):

def wrapper(request, *args, **kwargs):
# 获取请求的资源路径
path = request.path
# 如果请求的资源路径在设定的元组中就表示需要登录验证
if path in ('/vote/praise/', '/vote/criticize/'):
if 'username' not in request.session:
# session中没有username就重定向到登录页
return redirect('login')
return func(request, *args, **kwargs)

return wrapper
```

修改配置文件,激活中间件使其生效。

```Python
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'vote.middlewares.check_login_middleware',
]
```

0 comments on commit 3ad03f0

Please sign in to comment.