1

We have an application which does not support basic authentication yet. So I wrote a python script which sends a post request to login and then another request to a web service url. When I make the second call, my server is asking me to login again.

How can I use the same session to make the second call? Is it really possible? Below is the script

import requests

r = requests.post("https://myhost.com/login", verify=False, data={'IDToken1': 'administrator', 'IDToken2': 'TestPassw0rd', 'goto': 'https://myhost.com/', 'gotoInactive': 'https://myhost.com/login/?goto=https%3A%2F%2Fmyhost.com&login=inactive&user=administrator', 'gotoOnFail': 'https://myhost.com/login/?goto=https%3A%2F%2Fmyhost.com&login=fail&user=administrator'})
print r.status_code
print r.headers
print r.content

softwarePackages = requests.post("https://myhost.com/context-root/rest/softwarePackage/list", verify=False, data={'offset': 1, 'limit': 10, 'sortBy': 'importDate', 'ascending': 'false', 'platform': 'null'})
print softwarePackages.status_code
print softwarePackages.headers
print softwarePackages.content
0

1 Answer 1

3

Use Session object:

import requests

import requests

s = requests.Session()
r = s.post("https://myhost.com/login", verify=False, data={...})
softwarePackages = s.post(
    "https://myhost.com/context-root/rest/softwarePackage/list",
    verify=False, data={...}
)
print softwarePackages.status_code
print softwarePackages.headers
print softwarePackages.content

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance.

Sign up to request clarification or add additional context in comments.

1 Comment

@KrishnaChaitanya And in case you don't know, you can also store the cookie as a file to keep it persistent over several sessions after python script ends so you don't have to keep re-submitting login info! stackoverflow.com/questions/13030095/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.