python请求使用csrf登录到网站

时间:2017-11-20 13:01:16

标签: python-requests csrf

我正在使用Python3和我使用Python请求在https://competitions.codalab.org/accounts/login/登录的内容。

这是我的示例代码。

# -*- coding: utf-8 -*-
import requests
url_open = 'https://competitions.codalab.org/accounts/login'

sess = requests.Session()
sess.verify = False

sess.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate, sdch, br',
                'Accept-Language': 'zh-CN,zh;q=0.8',
                'Cache-Control': 'max-age=0',
                'Connection': 'keep-alive',
                'Host': 'competitions.codalab.org',
                'Referer': 'https',
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}

page = sess.get(url_open)
csrfToken = page.cookies['csrftoken']
print(csrfToken)

usrname = ***
passwd = ***

form_data = {
    'csrfmiddlewaretoken': csrfToken,
    'login': usrname,
    'password': passwd,
}
req = sess.post(url_open, data=form_data, cookies={
    'csrftoken': csrfToken
})
print(req.text)

我首先获得csrf,然后发布它。 但是这段代码无法登录codalab。 谁能告诉我为什么?

1 个答案:

答案 0 :(得分:1)

以下代码适用于django 1.9

import requests


client = requests.session()
client.get("http://127.0.0.1:8000/admin/login/")
csrftoken = client.cookies['csrftoken']

login_data = {'username':"admin",
    'password':"pass!", 
    'csrfmiddlewaretoken':csrftoken,
    'next': '/admin/'}

r1=client.post("http://127.0.0.1:8000/admin/login/",data=login_data)

print r1
<Response [200]>