1.中間鍵
2.csrf跨站請求僞造
3.裝飾器相關
4.auth模塊
5.settings 插拔式源碼 拓展
1.中間鍵
![](http://static.javashuo.com/static/loading.gif)
中間件:(默認有七個)
通俗講:django中間件相似於django的保安,來去都通過他;
大體流程:請求來時先通過中件才能到達django後端(urls,views,templates,models),
響應走時也要通過中間件才能到達web網關接口
做用:
1.網站全局的身份校驗,訪問頻率限制,權限校驗.....涉及全局,均可用到
2. django的中間件是全部web框架中作的最好的
django中間件中的五個自定義方法
*****
1.process_request()
規律:
1.請求來時,自上而下依次執行每一箇中間件裏的process_request的方法;
2.若是這個方法裏直接返回了HttpResponse對象,那麼會直接返回,再也不往下執行;
應用場景:訪問頻率限制,身份校驗
2.prosess_response()
規律:
1.必須將形參response返回, 該形參是返回前端的數據
2.響應走時會自下而上的執行每個中間件中的process_response方法
**
3.process_view(): 在url匹配成功以後,視圖函數以前 觸發
4.process_exception(): 視圖函授出錯以後觸發,自行執行
5.process_template_response():
規律:
1.返回的HttpResponse對象中必須包含render屬性纔會觸發,以下例:
def login(request):
print('我是誰?我從哪裏來?')
def render():
return HttpResponse('6666')
OBJ= HttpResponse('我要到那裏去?')
OBJ.render = render
return OBJ
注:1.寫中間件中時,只要有response這個形參,那就返回response(給前端的信息)
2.要想本身寫的中間件生效,必須先繼承MiddlewareMiXin
3.註冊中間件時,路徑不要寫錯
2.csrf跨站請求僞造
csrf跨站請求僞造:
釣魚網站: 製造一個更正常網站如出一轍的網站,騙取用戶輸入信息,eg轉帳交易..
釣魚原理: 在用戶輸入對方帳戶的input框中作些改動;好比這個input框 不設置name屬性,
而後在內部隱藏那個一個已經寫好有 name,value屬性的input框
預防思路:給用戶的form表單 中 放一個每次永遠不會重複的隨機字符串做爲惟一標識,
驗證經過再進行其餘操做,未經過,返回一個403
隨機字符串特色:
1.同一個瀏覽器每一次訪問都不同
2.不一樣瀏覽器 絕對不會重複
1. form表單發送 post請求時, 須要
{% csrf_token %}
2. ajax 發送post請求,避免csrf校驗的方法
首先:{% csrf_token %}
其次:
1.利用標籤查找獲取該input框的鍵值信息
{'username':'xxx','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}
2.直接寫
{'username':'xxx','csrfmiddlewaretoken':'{{csrf_token}}'}
3.將獲取隨機鍵值對的方法弄到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.裝飾器相關
1 裝飾器相關:
2 1.全局不校驗csrf,有幾個讓校驗 csrf_frotect
3 2.全局校驗csrf,有幾個不讓校驗 csrf_exempt
4 form django.utils.decorators import method_decorator
5 form django.views.decorators.csrf import csrf_exempt(不校驗),csrf_frotect(校驗)
6 給fbv裝飾時正常,給cbv裝飾時有如下兩種狀況發生
7 1.csrf_frotect 的 三種裝飾方式
8 # 第一種方式
9 # @method_decorator(csrf_protect,name='post') # 有效的
10 class MyView(View):
11 # 第三種方式
12 # @method_decorator(csrf_protect)
13 def dispatch(self, request, *args, **kwargs):
14 res = super().dispatch(request, *args, **kwargs)
15 return res
16
17 def get(self,request):
18 return HttpResponse('get')
19 # 第二種方式
20 # @method_decorator(csrf_protect) # 有效的
21 def post(self,request):
22 return HttpResponse('post')
23
24 注: 三種方法可隨意用其中的一種
25 2.csrf_exempt的兩種裝飾方式(只能給dispatch裝) 特例
26 @method_decorator(csrf_exempt,name='dispatch') # 第二種能夠不校驗的方式
27 class MyView(View):
28 # @method_decorator(csrf_exempt) # 第一種能夠不校驗的方式
29 def dispatch(self, request, *args, **kwargs):
30 res = super().dispatch(request, *args, **kwargs)
31 return res
32
33 def get(self,request):
34 return HttpResponse('get')
35
36 def post(self,request):
37 return HttpResponse('post')
38 小結:裝飾器中只要csrf_exemp是特例,其餘給cbv裝飾時都有三種方式
4.auth模塊
auth模塊:要用就用全套
相關簡介:
1.是一個跟用戶相關的功能模塊,用於 用戶的註冊,登陸,改密碼;
2.執行數據庫遷移命令後,會生成不少表, auth_user是跟用戶相關的表;
3.用 createsuperuser 建立超級用戶後,該用戶可登陸django admin後臺管理權限
功能功能:
1.查詢用戶
from django.contrib import auth
user_obj = auth.authenticate(username=username,password=password)
注:必需要用該方法,由於數據庫中的密碼是密文的,而你獲取的輸入倒是明文的,
不用該方法的話,永遠也匹配不上
2.記錄用戶狀態到session中
auth.login(request,user_obj)
3.判斷用戶是否登陸
request.user.is_authenticated 返回T/F
4.獲取用戶對象
request.user
注:登陸了獲取到用戶對象,沒登陸能夠拿到匿名對象
5.校驗用戶是否登陸
form django.contrib.auth.decorators import login_required
1.局部配置:
@login_required(login_url='/xxx/')
2.全局配置 在setting送文件中
LOGIN_URL = '/xxx/'
6.驗證密碼是否正確
request.user.check_password(old_opassword)
7.修改密碼
request.user.set_password(new_password)
request.user.save()
注: 修改密碼,必定要save保存,不然沒法生效
8.退出登陸
auth.logout(request) 效果至關於 request.session.flush()
9.註冊用戶
超級用戶的建立:
User.objects.create_superuser(username=username,password=password,email='123@qq.com')
普通用戶的建立:
User.objects.create_user(username=username,password=password)
自定義auth_user表:使用類繼承
from django.contrib.auth.models import AbstractUser
class Userinfo(AbstractUser):
phon = models.BigIntegerField()
avatar = models.CharField(max_length=32)
注:
1.自定義表只能添加新的字段,可是不要與原表中的字段重複(*****)
2.要在 配置文件中 設置 orm將要使用的表,而不是原來的默認表
AUTH_USER_MODEL = 'app01.Userinfo' # '應用名.類名'
3.執行數據庫遷移命令後,auth提供的功能還能夠照樣去用
5.settings 插拔式源碼 拓展
![](http://static.javashuo.com/static/loading.gif)
__init__.py文件中
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) # 對象調方法
settings.py文件
NOTIFY_LIST = [
'notify.email.Email',
'notify.msg.Msg',
'notify.wechat.WeChat',
'notify.qq.QQ',
]
功能相關
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
start.py 文件
import notify
notify.send_all('國慶放假了 記住放八天哦')