zoukankan      html  css  js  c++  java
  • Python Django 生命周期 中间键 csrf跨站请求伪造 auth认证模块 settings功能插拔式源码

    一 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 MiddlewareMixin
    
    2.自定义中间键的类必须要继承的父类
    MiddlewareMixin
    3.整体例:
    
    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 %}
    
    示例:
    <form action="" method="post">
        {% csrf_token %}
        
    <p>username:<input type="text" name="username"></p>
        <p>password:<input type="text" name="password"></p>
        <input type="submit">
    </form>

    #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文件 为例)
    <script src="{% static 'setjs.js' %}"></script>
    #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_exempt
    def login(request):
        return HttpResponse('login')

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

    #1.首先导入模块
    from django.views.decorators.csrf import csrf_exempt,csrf_protect
    #给fbv加装饰器:@csrf_protect
    @csrf_protect
    def 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 auth
    1.查询(条件至少要为2个) :对象=auth.authenticate(条件1,条件2)注意:自定义auth_user表后照样可使用该方法查询   
    user_obj = auth.authenticate(username=username,password=password)  # 必须要用 因为数据库中的密码字段是密文的 而你获取的用户输入的是明文
    
    2.记录状态:auth.login(request,对象)
    auth.login(request,user_obj)  # 将用户状态记录到session中,只要执行这句话任意位置都可以用:request.user拿到用户对象
    
    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_required
    def index(request):
        pass
    
    settings.py文件中配置
    LOGIN_URL = '/xxx/'  # 全配置,'/xxx/'为登录视图函数的url地址


    #创建用户和密码操作
    from django.contrib import auth
    1.密码:
    #验证密码是否正确: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 User
    def 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.py
    import notify
    
    notify.send_all('国庆放假了 记住放八天哦')
    
    #settings.py
    NOTIFY_LIST = [
        'notify.email.Email',
        'notify.msg.Msg',
        # 'notify.wechat.WeChat',
        'notify.qq.QQ',
    ]
    
    #_init_
    import settings
    import importlib
    
    
    def 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
  • 相关阅读:
    原根
    FFT
    bzoj3991[SDOI2015]寻宝游戏
    bzoj3990[SDOI2015]排序
    序列自动机
    bzoj4032[HEOI2015]最短不公共子串
    2015.8.28 字符串
    bzoj2821作诗
    bzoj2741【FOTILE模拟赛】L
    一个牛人给java初学者的建议
  • 原文地址:https://www.cnblogs.com/tfzz/p/11587957.html
Copyright © 2011-2022 走看看