【问题标题】:CSRF verification failed. Request aborted. (Python Request Module)CSRF 验证失败。请求中止。 (Python 请求模块)
【发布时间】:2020-02-28 20:15:23
【问题描述】:

我的views.py(Django项目)中有这个功能

def boardsJson(request):
    user=request.GET.get('user')
    password=request.GET.get('password')
    :
    :
    Bla Bla Bla 
    :
    :
    return HttpResponse("Login Success")

我正在尝试通过此请求模块登录。

import requests
URL = "http://35.196.206.72:8000/boardsJson/"
PARAMS = {
    'user':'1234567890',
    'password':'kak',
    }
r = requests.get(url = URL, params = PARAMS)
print(r.text)

在我使用 GET 方法登录之前,一切都很好。 但是,如果我使用 POST(我只是在每个地方都用“POST”替换了“GET”)方法,那么我会收到类似下面的消息。

  <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 âsame-originâ requests.</p>

所以请帮我解决它。 谢谢。

【问题讨论】:

    标签: python django django-rest-framework python-requests httprequest


    【解决方案1】:

    您需要在帖子中包含 CSRF 令牌,或者如果您要绕过它,请将 CSRF Exempt 装饰器添加到视图中。

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def boardsJson(request):
        user=request.GET.get('user')
        password=request.GET.get('password')
        :
        :
        Bla Bla Bla 
        :
        :
        return HttpResponse("Login Success")
    

    见https://docs.djangoproject.com/en/3.0/ref/csrf/#unprotected-view-needs-the-csrf-token

    【讨论】:

    • 感谢您的宝贵关注。我想使用第二个脚本(即船不是 Html 页面)登录。 r = requests.post(url = URL, params = PARAMS) 那么在第二个脚本中具体要做哪些改动呢?
    • 如果页面是一个普通的 django 表单,并且您尝试使用机器人登录,那么您需要向该页面发出两个请求。请求编号 1 - 向页面发出 GET 请求并提取 CSRF 令牌。我建议为 pypi.org/project/beautifulsoup4 使用 BeautifulSoup4。然后,您可以像现在一样使用用户名和密码以及从页面中提取的 CSRF 令牌提交 POST 请求。
    猜你喜欢
    • 2012-05-10
    • 2017-06-17
    • 1970-01-01
    • 2012-12-07
    • 2015-03-08
    • 1970-01-01
    • 2016-08-27
    相关资源
    最近更新 更多