2016-05-11 6 views
0

Вызванная функция взгляда, как этотDjango: проверка CSRF не удалась. Запрос прерван

def parsing(request): 
    url = request.POST['url'] 
    ... 
    return HttpResponse(json.dumps(resultDict)) 

Когда я делаю запрос на запись к нему через следующий код,

import requests 
url = 'http://tv.cntv.cn/video/C12278/a7ea7c0e810b4701bf1d3f5254b8a26a' 
c = requests.post("http://127.0.0.1:8000/VideoParser/", data={'url': url}) 
print(c.text) 

то запрос не удался, и он просто выдает следующий HTML код,

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
 
    <meta name="robots" content="NONE,NOARCHIVE"> 
 
    <title>403 Forbidden</title> 
 
    <style type="text/css"> 
 
    html * { padding:0; margin:0; } 
 
    body * { padding:10px 20px; } 
 
    body * * { padding:0; } 
 
    body { font:small sans-serif; background:#eee; } 
 
    body>div { border-bottom:1px solid #ddd; } 
 
    h1 { font-weight:normal; margin-bottom:.4em; } 
 
    h1 span { font-size:60%; color:#666; font-weight:normal; } 
 
    #info { background:#f6f6f6; } 
 
    #info ul { margin: 0.5em 4em; } 
 
    #info p, #summary p { padding-top:10px; } 
 
    #summary { background: #ffc; } 
 
    #explanation { background:#eee; border-bottom: 0px none; } 
 
    </style> 
 
</head> 
 
<body> 
 
<div id="summary"> 
 
    <h1>Forbidden <span>(403)</span></h1> 
 
    <p>CSRF verification failed. Request aborted.</p> 
 

 

 
    <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> 
 
    <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> 
 

 
</div> 
 

 
<div id="info"> 
 
    <h2>Help</h2> 
 
    
 
    <p>Reason given for failure:</p> 
 
    <pre> 
 
    CSRF cookie not set. 
 
    </pre> 
 
    
 

 
    <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when 
 
    <a 
 
    href="https://docs.djangoproject.com/en/1.9/ref/csrf/">Django's 
 
    CSRF mechanism</a> has not been used correctly. For POST forms, you need to 
 
    ensure:</p> 
 

 
    <ul> 
 
    <li>Your browser is accepting cookies.</li> 
 

 
    <li>The view function passes a <code>request</code> to the template's <a 
 
    href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> 
 
    method.</li> 
 

 
    <li>In the template, there is a <code>{% csrf_token 
 
    %}</code> template tag inside each POST form that 
 
    targets an internal URL.</li> 
 

 
    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use 
 
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code> 
 
    template tag, as well as those that accept the POST data.</li> 
 

 
    </ul> 
 

 
    <p>You're seeing the help section of this page because you have <code>DEBUG = 
 
    True</code> in your Django settings file. Change that to <code>False</code>, 
 
    and only the initial error message will be displayed. </p> 
 

 
    <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> 
 
</div> 
 

 
</body> 
 
</html>

Похоже, что причина отказа -

CSRF cookie не установлен.

Однако мое приложение не содержит никаких файлов cookie и шаблона в течение всего процесса, каждый может помочь устранить проблему? Я просто начинающий ученик Django.

+0

Просто простой 'csrf_exempt' декоратор будет делать эту работу. См. Мой ответ ниже. – alix

ответ

1

Вы используете POST-запрос, который снова защищен атаками CSRF, запрашивая токен.

Вы можете прочитать больше о CSRF токены в Django документы: https://docs.djangoproject.com/en/1.9/ref/csrf/

0

Вы можете использовать csrf_exempt декоратор для вашего зрения:

from django.views.decorators.csrf import csrf_exempt 

@csrf_exempt 
def parsing(request): 
    url = request.POST['url'] 
    ... 
    return HttpResponse(json.dumps(resultDict)) 

Из документов:

Этот декоратор помечает вид как освобожденный от защиты , обеспечиваемый промежуточным программным обеспечением.

Вы можете прочитать больше о защите CSRF here

0

У вас есть две опции сюда эту проблему

Первый: -

Если вы хотите использовать проверку подлинности CSRF необходимо нужно добавить печенье в каждый запрос, поступающий из внешнего интерфейса, для этого вам необходимо добавить следующий код sniipet в код вашего внешнего интерфейса

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'); 

и передать этот csrftoken в ваш вызов Ajax или угловое обслуживание в качестве заголовка.

Второй: -

И если ваш получать ошибки кросс-заголовка, так что если он отказывает запрос на Джанго сервер, то просто сделать pip install django-cors-headers и изменить settings.py с

INSTALLED_APPS = (
    ... 
    'corsheaders', 
    ... 
) 


MIDDLEWARE_CLASSES = (
    ... 
    'corsheaders.middleware.CorsMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    ... 
) 

Надежда так плохо помочь тебе !!

0

Просто удалите «django.middleware.csrf.CsrfViewMiddleware» из MIDDLEWARE_CLASSES в вашем settings.py

+0

Я верю, что удаляю 'django.middleware.csrf.CsrfViewMiddleware' из middlewares не является разумным. Это то, что означает декоратор 'csrf_exempt'. – alix