Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
P
Python-100-Days
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
huangkq
Python-100-Days
Commits
3ad03f02
Commit
3ad03f02
authored
Jun 02, 2019
by
jackfrued
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
更新了第46天的内容
parent
b74e0dea
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
41 additions
and
1 deletion
+41
-1
06.中间件的应用.md
Day41-55/06.中间件的应用.md
+41
-1
No files found.
Day41-55/06.中间件的应用.md
View file @
3ad03f02
...
...
@@ -5,7 +5,7 @@
```
Python
def praise_or_criticize(request: HttpRequest):
"""投票"""
if 'user' in request.session:
if 'user
name
' in request.session:
try:
tno = int(request.GET.get('tno', '0'))
teacher = Teacher.objects.get(no=tno)
...
...
@@ -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',
]
```
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment