user1781626
user1781626

Reputation:

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

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

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

Upvotes: 0

Views: 1399

Answers (1)

wenzul
wenzul

Reputation: 4058

You can also use Python for your first call. This will be much easier and take the advantages of 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.

Upvotes: 2

Related Questions