博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Django 生命周期 中间键 csrf跨站请求伪造 auth认证模块 settings功能插拔式源码...
阅读量:4658 次
发布时间:2019-06-09

本文共 11016 字,大约阅读时间需要 36 分钟。

一 django 生命周期

 

二 django中间键

1.什么是中间键

  官方的说法:中间件是一个用来处理Django的请求和响应的框架级别的钩子。它是一个轻量、低级别的插件系统,用于在全局范围内改变Django的输入和输出。每个中间件组件都负责做一些特定的功能。

        简单来说就相当于django门户,保安:它本质上就是一个自定义类,类中定义了几个方法。

        请求的时候需要先经过中间件才能到达django后端(urls,views,templates,models);

        响应走的时候也需要经过中间件才能到达web服务网关接口

2.中间件用途:

#1.网站全局的身份校验,访问频率限制,权限校验...只要是涉及到全局的校验你都可以在中间件中完成

#2.django的中间件是所有web框架中 做的最好的

3.注意:

  django默认有七个中间件,但是django暴露给用户可以自定义中间件并且里面可以写五种方法

  默认的七个中间键

 

 

 五个方法及执行时机:

##下面的从上往下还是从下往上都是按照注册系统来的## #需要我们掌握的方法有1.process_request(self,request)方法 规律:   1.请求来的时候 会经过每个中间件里面的process_request方法(从上往下)   2.如果方法里面直接返回了HttpResponse对象 那么不再往下执行,会直接原路返回并执行process_response()方法(从下往上)   基于该特点就可以做访问频率限制,身份校验,权限校验                                    2. process_response(self,request,response)方法  规律:   1.必须将response形参返回 因为这个形参指代的就是要返回给前端的数据   2.响应走的时候 会依次经过每一个中间件里面的process_response方法(从下往上)                                #需要了解的方法3. process_view(self,request,view_func,view_args,view_kwargs) 1.在路由匹配成功执行视图函数之前 触发执行(从上往下)                            4.process_exception(self, request, exception) 1.当你的视图函数报错时  就会自动执行(从下往上)                            5.process_template_response(self, request, response)  1.当你返回的HttpResponse对象中必须包含render属性才会触发(从下往上)  def index(request):    print('我是index视图函数')    def render():    return HttpResponse('什么鬼玩意')    obj = HttpResponse('index')    obj.render = render    return obj总结:你在书写中间件的时候 只要形参中有repsonse 你就顺手将其返回 这个reponse就是要给前端的消息

4.如何自定义中间件

#1.先创建与app应用同级目录的任意文件夹

#2.在文件夹内创建任意名py文件

#3.在py文件中编写自定义中间键(类)注意几个固定语法和模块导入

1.py文件中必须要导入的模块from django.utils.deprecation import MiddlewareMixin2.自定义中间键的类必须要继承的父类MiddlewareMixin3.整体例:
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class MyMdd(MiddlewareMixin):     def process_request(self,request):         print('我是第一个中间件里面的process_request方法')     def process_response(self,request,response):         print('我是第一个中间件里面的process_response方法')         return response     def process_view(self,request,view_func,view_args,view_kwargs):         print(view_func)         print(view_args)         print(view_kwargs)         print('我是第一个中间件里面的process_view方法')     def process_exception(self, request, exception):         print('我是第一个中间件里面的process_exception')     def process_template_response(self, request, response):         print('我是第一个中间件里面的process_template_response')         return response

#4.settings.py文件中配置自定义的中间件(整体示例)

三 csrf跨站请求伪造

1.钓鱼网站

#1.通过制作一个跟正儿八经的网站一模一样的页面,骗取用户输入信息 转账交易

从而做手脚
  转账交易的请求确确实实是发给了中国银行,账户的钱也是确确实实少了
  唯一不一样的地方在于收款人账户不对

#2.内部原理

  在让用户输入对方账户的那个input上面做手脚
  给这个input不设置name属性,在内部隐藏一个实现写好的name和value属性的input框
  这个value的值 就是钓鱼网站受益人账号

#3.防止钓鱼网站的思路

  网站会给返回给用户的form表单页面 偷偷塞一个随机字符串
  请求到来的时候 会先比对随机字符串是否一致 如果不一致 直接拒绝(403)

该随机字符串有以下特点

 1.同一个浏览器每一次访问都不一样
 2.不同浏览器绝对不会重复

2.实际用法

#这时候就不需要注释settings.py文件中的中间件了

#1.通过form表单提交数据实际用法

1.form表单发送post请求的时候  需要你做得仅仅书写一句话{
% csrf_token %}示例:
{
% csrf_token %}

username:

password:

#2.通过ajax提交数据的三种用法

1.现在页面上写{% csrf_token %},利用标签查找  获取到该input键值信息(不推荐)$('[name=csrfmiddlewaretoken]').val()例:                {
'username':'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}2.直接书写'{
{ csrf_token }}'例:{
'username':'jason','csrfmiddlewaretoken':'{
{ csrf_token }}'}3.你可以将该获取随机键值对的方法 写到一个js文件中,之后只需要导入该文件即可具体操作如下#1.static新建一个js任意名文件 存放以下代码 见其他代码#2.在html文件中引入刚才的js文件(以setjs.js文件 为例)#3.直接正常编写ajax代码总体示例$('#b1').click(function () { $.ajax({ url:'', type:'post', // 第一种方式 data:{
'username':'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}, // 第二种方式 data:{
'username':'jason','csrfmiddlewaretoken':'{
{ csrf_token }}'}, // 第三种方式 :直接引入js文件 data:{
'username':'jason'}, success:function (data) { alert(data) } })
View Code

第三种方式的js文件代码

function getCookie(name) {    var cookieValue = null;    if (document.cookie && document.cookie !== '') {        var cookies = document.cookie.split(';');        for (var i = 0; i < cookies.length; i++) {            var cookie = jQuery.trim(cookies[i]);            // Does this cookie string begin with the name we want?            if (cookie.substring(0, name.length + 1) === (name + '=')) {                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));                break;            }        }    }    return cookieValue;}var csrftoken = getCookie('csrftoken');function csrfSafeMethod(method) {  // these HTTP methods do not require CSRF protection  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}$.ajaxSetup({  beforeSend: function (xhr, settings) {    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {      xhr.setRequestHeader("X-CSRFToken", csrftoken);    }  }});
View Code

3.处理不同场景的校验方式(当settings.py的中间件 不键注释时:全局校验,注释时:全局不校验)

#1.当你网站全局都需要校验csrf的时候 有几个不需要校验该如何处理(全局校验,单个不校验)

#1.首先导入模块from django.views.decorators.csrf import csrf_exempt,csrf_protect#给fbv加装饰器:@csrf_exempt@csrf_exemptdef login(request):    return HttpResponse('login')

#2.当你网站全局不校验csrf的时候 有几个需要校验又该如何处理(全局不校验,单个校验)

#1.首先导入模块from django.views.decorators.csrf import csrf_exempt,csrf_protect#给fbv加装饰器:@csrf_protect@csrf_protectdef show(request):    return HttpResponse('lll')

#3.给cbv装饰的时候

from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt, csrf_protect# 这两个装饰器在给CBV装饰的时候 有一定的区别如果是csrf_protect那么有三种方式# 第一种方式# @method_decorator(csrf_protect,name='post')  # 有效的class MyView(View):    # 第三种方式    # @method_decorator(csrf_protect)    def dispatch(self, request, *args, **kwargs):        res = super().dispatch(request, *args, **kwargs)        return res    def get(self, request):        return HttpResponse('get')    # 第二种方式    # @method_decorator(csrf_protect)  # 有效的    def post(self, request):        return HttpResponse('post')如果是csrf_exempt只有两种(只能给dispatch装)特例@method_decorator(csrf_exempt, name='dispatch')  # 第二种可以不校验的方式class MyView(View):    # @method_decorator(csrf_exempt)  # 第一种可以不校验的方式    def dispatch(self, request, *args, **kwargs):        res = super().dispatch(request, *args, **kwargs)        return res    def get(self, request):        return HttpResponse('get')    def post(self, request):        return HttpResponse('post')

拓展:cbv登录装饰器的几种方式

CBV加装饰器# @method_decorator(login_auth,name='get')  # 第二种 name参数必须指定class MyHome(View):    @method_decorator(login_auth)  # 第三种  get和post都会被装饰    def dispatch(self, request, *args, **kwargs):        super().dispatch(request, *args, **kwargs)    # @method_decorator(login_auth)  # 第一种    def get(self, request):        return HttpResponse('get')    def post(self, request):        return HttpResponse('post')

四 Auth认证模块

1.什么是Auth模块:Auth模块是Django自带的用户认证模块,它默认使用 auth_user 表来存储用户数据(可以通过其他操作来使用别的表)。主要解决开发一个网站用户系统的注册、用户登录、用户认证、注销、修改密码等功能。执行数据库迁移命令之后  会生成很多表  其中的auth_user是一张用户相关的表格。

2.如何使用

#1.基本使用

#导入模块from django.contrib import auth1.查询(条件至少要为2个) :对象=auth.authenticate(条件1,条件2)   user_obj = auth.authenticate(username=username,password=password)  # 必须要用 因为数据库中的密码字段是密文的 而你获取的用户输入的是明文2.记录状态:auth.login(request,对象)auth.login(request,user_obj)  # 将用户状态记录到session中3.注销:auth.logout(request)auth.logout(request)  # request.session.flush()4.判断用户是否登录 ,如果执行过了 auth.login(request,对象) 结果就为Ture print(request.user.is_authenticated)5.登录认证装饰器2种方式:校验用户是否登录第一种方式:from django.contrib.auth.decorators import login_required@login_required(login_url='/xxx/')  # 局部配置,'/xxx/'为登录视图函数的url地址def index(request):    pass第二种方式:from django.contrib.auth.decorators import login_required@login_requireddef index(request):    passsettings.py文件中配置LOGIN_URL = '/xxx/'  # 全配置,'/xxx/'为登录视图函数的url地址
from django.contrib import auth1.密码:#验证密码是否正确:request.user.check_password(密码)is_right = request.user.check_password(old_password)#修改密码request.user.set_password(new_password)request.user.save()  # 修改密码的时候 一定要save保存 否则无法生效#示例# 修改用户密码@login_required # 自动校验当前用户是否登录  如果没有登录 默认跳转到 一个莫名其妙的登陆页面def set_password(request):    if request.method == 'POST':        old_password = request.POST.get('old_password')        new_password = request.POST.get('new_password')        # 先判断原密码是否正确        is_right = request.user.check_password(old_password)  # 将获取的用户密码 自动加密 然后去数据库中对比当前用户的密码是否一致        if is_right:            print(is_right)            # 修改密码            request.user.set_password(new_password)            request.user.save()  # 修改密码的时候 一定要save保存 否则无法生效    return render(request,'set_password.html')2.创建用户from django.contrib.auth.models import User# User.objects.create_user(username =username,password=password)  # 创建普通用户User.objects.create_superuser(username =username,password=password,email='123@qq.com')  # 创建超级用户  邮箱必填示例:from django.contrib.auth.models import Userdef register(request):    if request.method == 'POST':        username = request.POST.get('username')        password = request.POST.get('password')        user_obj = User.objects.filter(username=username)        if not user_obj:            # User.objects.create(username =username,password=password)  # 创建用户名的时候 千万不要再使用create 了            # User.objects.create_user(username =username,password=password)  # 创建普通用户            User.objects.create_superuser(username =username,password=password,email='123@qq.com')  # 创建超级用户    return render(request,'register.html')
密码和创建用户

#2.自定义auth_user表

在models.py文件中配置#1.导入模块from django.contrib.auth.models import AbstractUser#2.建表# 第二种方式   使用类的继承class Userinfo(AbstractUser):    # 千万不要跟原来表中的字段重复 只能创新    phone = models.BigIntegerField()    avatar = models.CharField(max_length=32)#3.一定要在配置文件settings.py中告诉django  orm不再使用auth默认的表  而是使用你自定义的表AUTH_USER_MODEL = 'app01.Userinfo'  # '应用名.类名'#4.1.执行数据库迁移命令,所有的auth模块功能 全部都基于你创建的表 ,而不再使用auth_user

五 settings功能插拔式源码

#start.pyimport notifynotify.send_all('国庆放假了 记住放八天哦')#settings.pyNOTIFY_LIST = [    'notify.email.Email',    'notify.msg.Msg',    # 'notify.wechat.WeChat',    'notify.qq.QQ',]#_init_import settingsimport importlibdef send_all(content):    for path_str in settings.NOTIFY_LIST:  # 1.拿出一个个的字符串   'notify.email.Email'        module_path,class_name = path_str.rsplit('.',maxsplit=1)  # 2.从右边开始 按照点切一个 ['notify.email','Email']        module = importlib.import_module(module_path)  # from notity import msg,email,wechat        cls = getattr(module,class_name)  # 利用反射 一切皆对象的思想 从文件中获取属性或者方法 cls = 一个个的类名        obj = cls()  # 类实例化生成对象        obj.send(content)  # 对象调方法#class Email(object):    def __init__(self):        pass  # 发送邮件需要的代码配置    def send(self,content):        print('邮件通知:%s'%content)class  Msg(object):    def __init__(self):        pass  # 发送短信需要的代码配置    def send(self,content):        print('短信通知:%s' % content)class QQ(object):    def __init__(self):        pass  # 发送qq需要的代码准备    def send(self,content):        print('qq通知:%s'%content)class WeChat(object):    def __init__(self):        pass  # 发送微信需要的代码配置    def send(self,content):        print('微信通知:%s'%content)
View Code

转载于:https://www.cnblogs.com/tfzz/p/11587957.html

你可能感兴趣的文章
[刷题]Codeforces 785D - Anton and School - 2
查看>>
四川红油的制法
查看>>
Java重写《C经典100题》 --21
查看>>
【Android基础】Fragment 详解之Fragment生命周期
查看>>
链表(裸题)
查看>>
11运算符重载
查看>>
磁盘系统的管理
查看>>
C/S
查看>>
Http Get/Post请求的区别
查看>>
STM32一键下载电路设计原理
查看>>
C语言中函数返回字符串的四种方法
查看>>
10月区块链领域投融资事件盘点
查看>>
Mybatis缓存策略
查看>>
卷积的意义【转】
查看>>
android图形系统详解五:Android绘制模式
查看>>
[剑指offer] 23. 二叉搜索树的后序遍历序列
查看>>
canvas绘画交叉波浪
查看>>
Linux 内核分析
查看>>
试一下:XP ( SP2 ) 本身就支持查杀流氓软件!
查看>>
centos6(7) minimal 基本环境配置
查看>>