django-ajax之post方式

post方式不一樣於get方式能夠被django直接獲得,由於django爲post加入了csrf保護,  詳細的文檔地址https://docs.djangoproject.com/en/dev/ref/csrf/html

註釋:在最新版本中,在setting.py裏'django.middleware.csrf.CsrfViewMiddleware',默認是使用中的,若是沒有請自行添加,而且確保此引用在其餘全部viewware前面ajax

 

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',//this line is vsrf 
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_cas.middleware.CASMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)django

 

若是想避過csrf檢測這一層直接使用post的話,有幾種方法:json

1 須要在views.py裏要出發post請求的函數前加入@csrf_exempt ,以前要引入from django.views.decorators.csrf import csrf_exemptcookie

2 在 settings.py 中 MIDDLEWARE_CLASSES 中 註釋掉'django.middleware.csrf.CsrfViewMiddleware'session

 

說下正確使用csrf的方法 :函數

對於ajax.post方法,須要在ajax方法觸發前加入一段js,這段我理解是用來生成不一樣的token,可是很好奇若是禁掉了cookie會怎樣我沒研究.post

 

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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}ui

ajax方法 :this

$.ajax({
url: "ticket/operation/?action=get_vmlist",
data: { 'env': env, 'subenv': subenv },
type: "post",
dataType: 'json',
beforeSend: function (xhr, settings) {

//此處調用剛剛加入的js方法
var csrftoken = getCookie('csrftoken'); 
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
 
}
},
success: function (data) {
 
},
complete: function () {
 
},
error: function (er) {
 
}
});

view.py:

def ticket_handler(request):  

if request.method == 'POST':
  if request.GET['action'] == 'get_vmlist':
    try:

      d = {}  
      env = request.POST['env'] 

      print env //這裏就能夠看到env的值被正確傳遞給後臺了

      d['Result'] = 'Fail'
      s = json.dumps(d)
      return HttpResponse(s)

btw:

能夠顯示對單個view函數進行csrf保護,
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def my_view(request): c = {} # ... return render(request, "a_template.html", c)
相關文章
相關標籤/搜索