[英]How to send a cookie with requests.get or requests.post in python?
I'm having a really hard time converting the following bash script to python 我很难将以下bash脚本转换为python
The following works: 以下作品:
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
Now in Python, I'm not sure how to complete the cookies part 现在,在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
You can also use Python for your first call. 您也可以使用Python进行首次通话。 This will be much easier and take the advantages of python. 这将容易得多,并利用python的优势。 It's not tested. 尚未测试。
#!/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
If you want the cookie to persist look here . 如果您希望cookie继续存在,请查看此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.