无法使用Python请求执行多个POST

时间:2015-12-28 22:56:21

标签: python authentication python-requests restful-authentication

我正在尝试以编程方式登录,但收到401错误。这是我的代码:

 with requests.Session() as s:
    resp = s.get(dydraLogin)
    soup = BeautifulSoup(resp.text,"html5lib")
    csrfToken = soup.find('meta',{'name':'csrf-token'}).get('content')
    # print csrfToken
    payloadLogin = {
    'account[login]':key,
    'account[password]':'',
    'csrfmiddlewaretoken':csrfToken,
    'next':'/'  
    }
    payloadPOST = {
    'url': sesameURL
    }
    headersPOST = {
    'Content-Type': 'application/n-quads',
    'Referer': dydraLogin,
    'User-Agent': 'python',
    'account[login]':key,
    'account[password]':'',
    'id':csrfToken,
    'csrfmiddlewaretoken':csrfToken,
    'next':'/',
    }
    # paramsPOST = {
    # 'auth_token': key
    # }
    # print payload
    p = s.post(dydraLogin,data=payloadLogin, headers=dict(Referer=dydraLogin))
    print p
    try:
        q = s.post(dydraUrl,data=payloadPOST, headers=headersPOST)
        print q.text
    except requests.exceptions.RequestException as e:
        print e

这是输出:

<Response [200]>
401 Unauthorized

我能够登录,但后续的数据POST失败。对于正确执行第二个POST,我需要做些什么?

更新1

我尝试重新生成csrfToken,但错误仍然存​​在:

    url='http://dydra.com/username'
    resp_new = s.get(url)
        # print resp_new.text
        soup_new = BeautifulSoup(resp_new.text,"html5lib")
        csrfToken_new = soup_new.find('meta',{'name':'csrf-token'}).get('content')
        print 'csrf_new: ' + csrfToken_new

        payloadPOST = {
        'url': sesameURL,
        'account[login]':key,
        'account[password]':'',
        'csrfmiddlewaretoken':csrfToken_new,
        'next':'/',
        }   

        headersPOST = {
        'User-Agent': 'python',
        'Content-Type': 'application/n-quads',
        'Referer': dydraLogin,
        }

        # paramsPOST = {
        # 'auth_token': key
        # }
        # print payload

        try:
            q = s.post(dydraUrl,data=payloadPOST, headers=headersPOST)
            print q.text
        except requests.exceptions.RequestException as e:
            print e

更新2:

如果我在网址中使用身份验证密钥,我可以访问dydraUrl:

print s.get('http://dydra.com/username/repositories/rep_name/statements?auth_token=<key>').text

但是,当我在payloadPOST中使用URL时,401错误仍然存​​在。

0 个答案:

没有答案