中间件和auth模块

中间件

1.什么是中间件
中间件顾名思义,是介于requestresponse处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出。因为改变的是全局,所以需要谨慎实用,用不好会影响到性能 
2.中间件的作用
如果你想修改请求,例如被传送到view中的HttpRequest对象。 或者你想修改view返回的HttpResponse对象,这些都可以通过中间件来实现。 可能你还想在view执行之前做一些操作,这种情况就可以用 middleware来实现。 Django默认的中间件:(在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件) 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', ] 
3.自定义中间件
from django.utils.deprecation import MiddlewareMixin
class MyMiddle(MiddlewareMixin): def process_request(self, request): # request时触发 print('middle request') def process_response(self, request, response): # response时触发 print('process_response') return response def process_view(self, request, callback, callback_args, callback_kwargs): # 路由到视图函数之间触发 print('process_view') # callback(request) def process_exception(self, request, exception): # 报错时触发 return HttpResponse(exception) def process_template_response(self, request, response): # return views.类()时触发 print('i am process_template_response') print(response) return views.Test()

4.中间件应用场景
1.做IP访问频率限制
某些IP访问服务器的频率过高,进行拦截,比如限制每分钟不能超过20次。 2.URL访问过滤 如果用户访问的是login视图(放过) 如果访问其他视图,需要检测是不是有session认证,已经有了放行, 没有返回login,这样就省得在多个视图函数上写装饰器了! 
5.CSRF_TOKEN跨站请求伪造
在form表单中应用:
<form action="" method="post"> {% csrf_token %} <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="text" name="password"></p> <p><input type="submit"></p> </form> 
在Ajax中应用:
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <script src="/static/jquery-3.3.1.js"></script> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="text" name="password" id="pwd"></p> <p><input type="submit"></p> </form> <button class="btn">点我</button> </body> <script> $(".btn").click(function () { $.ajax({ url: '', type: 'post', data: { 'name': $('[name="name"]').val(), 'password': $("#pwd").val(), 'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val() }, success: function (data) { console.log(data) } }) }) </script> </html> 
全站禁用

注释掉中间件 'django.middleware.csrf.CsrfViewMiddleware',

局部禁用
FBVfrom django.views.decorators.csrf import csrf_exempt,csrf_protect
# 不再检测,局部禁用(前提是全站使用) # @csrf_exempt # 检测,局部使用(前提是全站禁用) # @csrf_protect def csrf_token(request): if request.method=='POST': print(request.POST) return HttpResponse('ok') return render(request,'csrf_token.html') 
CBVfrom django.views import View
from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.utils.decorators import method_decorator @method_decorator(csrf_exempt,name='dispatch') class Foo(View): def dispatch(self, request, *args, **kwargs): res = super().dispatch(request, *args, **kwargs) return res def get(self,request): pass def post(self,request): pass 

Auth模块

1.Auth模块常用方法
from django.contrib import auth
authenticate(request, username=name, password=pwd)      用户认证功能,返回一个 User 对象 login(request, user) 在后端为该用户生成相关session数据 logout(request) 当前请求的session信息会全部清除 is_authenticated() 判断当前请求是否通过了认证 login_requierd() 装饰器,某个视图添加登录校验 该装饰器需要在settings中添加登录地址 LOGIN_URL = '/login/' # 这里配置成你项目登录页面的路由 create_user() 创建新用户 create_superuser() 创建新的超级用户 check_password(password) 提供的一个检查密码是否正确的方法 set_password(password) 修改密码,设置完一定要调用用户对象的save方法 
2.User对象的属性
User对象属性:username, password

is_staff 用户是否拥有网站的管理权限. is_active 是否允许用户登录, 设置为 False,可以在不删除用户的前提下禁止用户登录。 
3.扩展默认的auth_user表
modelfrom django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser): # 继承父类,并派生新需要的字段 nid = models.AutoField(primary_key=True) phone = models.CharField(max_length=11, null=True, unique=True) def __str__(self): return self.username 注意,需要在setting中添加AUTH_USER_MODEL = "app名.UserInfo"

转载于:https://www.cnblogs.com/luck-L/p/9664711.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值