如何在python中发送带有requests.get或requests.post的cookie?

时间:2014-10-14 00:16:48

标签: python python-requests

我很难将以下bash脚本转换为python

以下作品:

USERNAME=username
PASSWORD=password
COOKIE_FILE=app_cookies
echo $COOKIE_FILE
res=`curl -s -L -c $COOKIE_FILE -b $COOKIE_FILE -d "j_username=$USERNAME&j_password=$PASSWORD" http://localhost:8080/j_security_check | grep "Authenticated" | wc -l`
if [ $res -gt 0 ]; then
    echo $COOKIE_FILE
    curl -b $COOKIE_FILE http://localhost:8080/data
fi
rm -f $COOKIE_FILE

现在在Python中,我不确定如何完成cookie部分

COOKIE_FILE="app_cookies"
USERNAME=username
PASSWORD=password
result = os.system("curl -s -L -c " + COOKIE_FILE + " -b " + COOKIE_FILE + " -d \"j_username=" + username + "&j_password=" + password 
                    + "\" http://localhost:8080/j_security_check | grep \"Authenticated\" | wc -l")
# Authenticated
if result == 0:
    # it reaches here fine
    cookies = ????
    response = requests.get(url='http://localhost:8080/data', 
                        cookies=?????)
    print response.status_code
    print response.text

1 个答案:

答案 0 :(得分:1)

您也可以使用Python进行首次通话。这将更容易并利用python的优势。它没有经过测试。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
session = requests.session()
payload = {'j_username': username, 'j_password': password}
r = session.post(url='http://localhost:8080/j_security_check', data=payload)

if u"Authenticated" in r.text:
    data = session.get(url='http://localhost:8080/data')
    print data, data.text

如果您希望Cookie保持不变,请查看here