通过python请求登录时收到403个CSRF验证失败
我使用Pinax,并尝试使用通过python请求登录时收到403个CSRF验证失败,python,django,pinax,http-request,python-requests,Python,Django,Pinax,Http Request,Python Requests,我使用Pinax,并尝试使用请求模块对帐户项目执行登录测试 是我干的 def test001_login(self): #cookies = {'csrftoken': 'a8356fd05b25fad7004994fd5da89596'} r = requests.post(self.loginurl, data={'username':self.username, 'password': self.password}, auth=(self.username, self.pa
请求
模块对帐户
项目执行登录测试
是我干的
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>
故障原因:
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)
没有CSRF或会话cookie。
通常,当存在真正的跨站点请求伪造时,或者
未正确使用。对于POST表单,您需要
确保:
我试图插入
cookies
,但它仍然给了我403个错误。您的帖子没有将CSRF令牌交给登录名。这是否有效:
CSRF的工作原理是在表单中添加一个隐藏字段,其中包含一个不同的令牌,然后在表单发布时对其进行测试。您收到此错误是因为您没有在帖子中包含令牌。您可以绕过它,或者关闭它,或者使用“适当的”单元测试工具
如果您正在进行测试驱动开发,可能值得一看谢谢。我也打算这么做。我应该这样进口吗<代码>从django.middleware导入csrf