2012-03-13 25 views
0

我使用Pinax,並且我試圖使用requests模塊對account項目執行登錄測試。當通過python請求登錄時收到403 CSRF驗證失敗

我沒有返回此

def test001_login(self): 
    #cookies = {'csrftoken': 'a8356fd05b25fad7004994fd5da89596'} 
    r = requests.post(self.loginurl, data={'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True) 

    print r.status_code 
    print r.text 
    print r.cookies 

的Cookie是空的!用get方法,我得到一個cookie。什麼導致這個問題?

r.text結果:

<p>Reason given for failure:</p> 
    <pre> 
    No CSRF or session cookie. 
    </pre> 

    <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when 
    <a 
    href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's 
    CSRF mechanism</a> has not been used correctly. For POST forms, you need to 
    ensure:</p> 

我試圖在cookies堅持,但它還是給了我403錯誤。

回答

2

您的文章沒有將CSRF令牌交給登錄。這是否正常工作:

r = requests.post(self.loginurl, data={'csrf_token': django.middleware.csrf.get_token(), 'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True) 
+0

謝謝。我也打算這樣做。我應該像這樣導入嗎? '從django.middleware import csrf' – CppLearner 2012-03-13 22:22:50

+0

是的,這是正確的。 – Furbeenator 2012-03-13 22:28:36

0

CSRF的工作原理是在表單發佈時向表單中添加一個包含變量標記的隱藏字段,然後對其進行測試。你得到這個錯誤是因爲你沒有在帖子中包含令牌。你可以解決它,或關閉它,或使用「適當的」單元測試的東西。

See the CSRF documentation

可能是值得仰視Client如果你正在做測試驅動開發

相關問題