一 django 生命周期html
二 django中间键前端
1.什么是中间键web
官方的说法:中间件是一个用来处理Django的请求和响应的框架级别的钩子。它是一个轻量、低级别的插件系统,用于在全局范围内改变Django的输入和输出。每一个中间件组件都负责作一些特定的功能。ajax
简单来讲就至关于django门户,保安:它本质上就是一个自定义类,类中定义了几个方法。数据库
请求的时候须要先通过中间件才能到达django后端(urls,views,templates,models);django
响应走的时候也须要通过中间件才能到达web服务网关接口后端
2.中间件用途:浏览器
#1.网站全局的身份校验,访问频率限制,权限校验...只要是涉及到全局的校验你均可以在中间件中完成
#2.django的中间件是全部web框架中 作的最好的微信
3.注意:cookie
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) } })
第三种方式的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); } } });
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) 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_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)