2016-09-14 77 views
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) 
+0

這就是一個重複http://stackoverflow.com/questions/13567507/passing-csrftoken-with-python-requests – jabez

+0

我試圖把引薦網址在頭,但我仍然得到同樣的錯誤。我也更新了這個問題。 – Gaurang

回答

0

我在標題中提供了其他參數,我認爲這是創建問題。我刪除了所有其他參數,只保留引薦來源,現在它正在工作。

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) 
相關問題