【发布时间】:2017-01-22 06:43:16
【问题描述】:
我正在尝试使用 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)
【问题讨论】:
-
我尝试将引用 URL 放在标题中,但是我仍然收到相同的错误。我也更新了问题。
标签: python django python-2.7 django-forms request