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

如何在python中发送带有requests.get或requests.post的cookie?,python,python-requests,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 | gre

我很难将下面的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中,我不确定如何完成cookies部分

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

您还可以在第一次调用时使用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保持外观。

在Python脚本中,第一次调用使用
curl
,第二次调用使用
requests.get
,有什么原因吗?既然它似乎有效,为什么不同时使用
curl
?另外,我相信
subprocess.Popen()
是调用CLI命令的更好方法。谢谢!如果通过,我添加了一个print语句,当我打印r.cookies时,我运行bash脚本创建文件,其中有一些带有workerthmrglujxfx9b2bk5lg6apyou're welcome的文本。所以第二个电话不能正常工作?我已经编辑了我的帖子,所以通过一个会话,它现在应该可以工作了。很好,您保存了我的生命软件,其中包含发送到
localhost
的请求和会话cookie。如果web服务器在cookie的域属性中返回
localhost
,则将拒绝此类cookie。正确的域属性值应为
localhost.local
。最好使用
127.0.0.1
而不是
localhost