Django中间件、Auth认证

中间件

一:什么是中间件

介于request与response处理之间的一道处理过程

二:中间件的作用

如果你想修改请求,例如被传送到view中的HttpRequest对象。 或者你想修改view返回的HttpResponse对象,这些都可以通过中间件来实现。

可能你还想在view执行之前做一些操作,这种情况就可以用 middleware来实现。

默认的中间件如下,在settings配置文件中:

MIDDLEWARE = [
#settings里默认的中间件
'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',
#自定义添加的中间件
'app01.mymid.MyMid1',
'app01.mymid.MyMid2',
]

每一个中间件都有具体的功能

三:自定义中间件

Django中间件、Auth认证

第一步:导入MiddlewareMixin,新建的类必须继承它

from django.utils.deprecation import MiddlewareMixin

第二步:自定义中间件,新建一个自定义中间件的py文件例如下面的mymid.py,在里面自定义中间件类

#导入MiddlewareMixin模块
from django.utils.deprecation import MiddlewareMixin #自定义的类一定要继承MiddlewareMixin
class MyMid1(MiddlewareMixin):
def process_request(self,request):
print('MyMid1====process_request') def process_response(self, request, response):
print('MyMid1====process_response')
return response class MyMid2(MiddlewareMixin):
def process_request(self,request):
print('MyMid2====process_request') def process_response(self, request, response):
print('MyMid2====process_response')
return response

Django中间件、Auth认证

第三步:在view中定义一个视图函数(index),用于下面验证中间件与视图函数,输出的先后顺序

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

def index(request):
print("中间件")
return HttpResponse("中间件验证")

第四步:在settings.py的MIDDLEWARE里面注册自己定义的中间件

Django中间件、Auth认证

结果:

MyMid1====process_request  #中间键的request请求是位于视图函数之前的
MyMid2====process_request
中间件
MyMid2====process_response
MyMid1====process_response
Performing system checks...

  

 Auth认证:

第一步:加载自带的db.sqlite3数据库(加载自带的数据库文件)

E:\PycharmProjects\day中间件>python3 manage.py makemigrations
No changes detected #因为是用默认的,并没有再models里面做一些其他的更改 E:\PycharmProjects\day中间件>python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
...

  

第二步:

Django中间件、Auth认证

第三步:给auth_user插入用户数据信息,用于后面认证登录:

terminal视口里面输入,在数据库里设置一个账号、密码:

python3 manage.py createsuperuser

E:\PycharmProjects\day中间件>python3 manage.py createsuperuser
Username (leave blank to use 'administrator'): yzz
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is entirely numeric. #密码会有复杂性要求
Password:
Password (again):
This password is too common.
This password is entirely numeric.
Password:
Password (again):
Superuser created successfully.

password:是加密的

is_superuser: 1表示管理员账号 0表示普通用户

Django中间件、Auth认证

 

 

上一篇:iOS 内购讲解


下一篇:$Django 中间件 csrf