0

我使用 Pinax,我正在尝试使用模块对account项目执行登录测试。requests

我做了这个

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 错误。

4

2 回答 2

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)
于 2012-03-13T21:59:29.927 回答
0

CSRF 的工作原理是在表单中添加一个包含可变标记的隐藏字段,然后在发布表单时对其进行测试。您收到此错误是因为您没有在帖子中包含令牌。您可以解决它,或将其关闭,或使用“适当的”单元测试材料。

请参阅 CSRF 文档

如果您正在进行测试驱动开发,可能值得查找Client

于 2012-03-14T05:02:32.913 回答