Django使用Request模块提交表单,CSRF验证失败



我正在尝试使用Python请求模块提交一种形式的django应用程序,但是它给了我以下错误

错误码:403
消息:CSRF验证失败。请求中止。

我试图使用json.dumps()转换JSON并发送请求,但我得到同样的错误。

我不确定,丢失了什么。当我使用UI提交表单时,它工作得很好。我拦截的请求使用Postman插件以及请求我有形式是相同的。

import requests
session = requests.session()
session.get("http://localhost:8000/autoflex/addresult/")
csrf_token = session.cookies["csrftoken"]
print csrf_token
cookie = "csrftoken=%s" % csrf_token
headers = {"Content-Type": "Application/x-www-form-urlencoded",
           "Cookie": cookie,
           "Accept-Encoding": "gzip, deflate",
           "Connection": "keep-alive",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
           "Referer": "http://localhost:8000/autoflex/addresult/"}
data = {"xml_url": xml_url, "csrfmiddlewaretoken": csrf_token}
result = session.post("http://localhost:8000/autoflex/addresult/", data=data, headers=headers)
print result.request.body
print result.request.headers
print(result.status_code, result.reason, result.content)

我在标题中提供了其他参数,我认为这正在创建问题。我删除了所有其他参数,只保留了referer,现在它工作了。

import requests
session = requests.session()
session.get("http://localhost:8000/autoflex/addresult/")
csrf_token = session.cookies["csrftoken"]
data = {"xml_url": xml_url, "csrfmiddlewaretoken": csrf_token}
result = session.post("http://localhost:8000/autoflex/addresult/", data=data, headers={"Referer": "http://localhost:8000/autoflex/addresult/"})
print result.request.body
print result.request.headers
print(result.status_code, result.reason, result.content)

最新更新