0
我试图用Python请求模块提交Django应用程序的一种形式,但它给了我下面的错误Django的使用请求模块提交表单,CSRF验证失败
错误代码:403
消息:CSRF验证失败。请求中止。
我试图转换在JSON使用json.dumps()
并发送请求,但是我得到相同的错误。
我不确定,缺少的是什么。当我使用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)
这就是一个重复http://stackoverflow.com/questions/13567507/passing-csrftoken-with-python-requests – jabez
我试图把引荐网址在头,但我仍然得到同样的错误。我也更新了这个问题。 – Gaurang