python-requests和django-CSRF验证失败。请求中止 [英] python-requests and django - CSRF verification failed. Request aborted

查看:342
本文介绍了python-requests和django-CSRF验证失败。请求中止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django服务器来上传文件,当我使用浏览器时,我可以毫无问题地上传文件。

I have a django server to upload files and when I use a browser, I can upload the file without problems.

但是如果我使用python-requests命令,它告诉我CSRF验证失败。请求中止。 python-requests代码如下:

But if I use the python-requests commands, it tells me CSRF verification failed. Request aborted. The python-requests code is as followed:

    #upload via HTTP
    file = {"docfile": open(fullfilename, "rb")}
    s = requests.Session()
    r = s.get(dhost)
    r = s.post(dhost, files=file)

如果我执行我的代码,则会得到代码403,并且错误CSRF验证失败。请求中止。给出失败原因:CSRF令牌丢失或不正确。

If I execute my code, I get the code 403 and the error CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.

但是,如果我查看发送的标头,则会设置cookie:

But if I look in the header I sent, I have the cookie set:

CaseInsensitiveDict({'Content-Length': u'84169', 
'Accept-Encoding': 'gzip, deflate, compress', 
'Accept': '*/*', 
'User-Agent': 'python-requests/2.0.1 CPython/2.7.3 Linux/3.6.11+', 
'Cookie': 'csrftoken=GOOIsG89i5oMCJO6594algTXooxoUeoL', 
'Content-Type': 'multipart/form-data; boundary=86ada00b4f6c41d5997293cce7a53b6b'})

能否请您告诉我该如何工作?

Could you please tell me what I should do in order to have this to work?

谢谢,

John。

推荐答案

实际上一切正常,您只需要了解csrf的工作原理即可。当您在浏览器中加载页面时,您会在 {%csrf_token%} 中获得一个csrf令牌,因此,当您将数据发送到服务器时,您也会同时发送csrf

It's actually all working fine, you just have to understand how csrf works. When you load the page in your browser, you get a csrf token inside {% csrf_token %}, So when you send the data to the server, you also send along the csrf token.

使用请求时,您会在 get部分中获取cookie,但不会将其与 post一起发送。如果没有它,您将发送一个根本没有令牌的发帖请求,这意味着CSRF验证错误。要解决它,请尝试以下代码:

When you use requests, you're getting the cookie in the 'get' part, but you're not sending it along with your 'post'. without it, you're just sending a post request with no token at all, which means a CSRF verification error. To solve it, try this code:

file = {"docfile": open(fullfilename, "rb")}
s = requests.Session()
r1 = s.get(dhost)
csrf_token = r1.cookies['csrftoken']
r2 = s.post(dhost, files=file, data={'csrfmiddlewaretoken': csrf_token}, headers=dict(Referer=dhost))

如果仅供您自己使用,您可以使用csrf_exampt在该视图上禁用csrf:

If this is just for your own usage, you can disable csrf on that view using csrf_exampt:

@csrf_exempt
def my_view(request):
   ...whateva...

但是请注意,这不是如果您打算启动服务器并向公众开放,则为推荐的解决方案

But note that this isn't a recommended solution if you plan to launch your server and open it to the public

这篇关于python-requests和django-CSRF验证失败。请求中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆