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
Krishna Chaitanya
  • 2,533
  • 4
  • 40
  • 74

1 Answers1

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    @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! http://stackoverflow.com/questions/13030095/how-to-save-requests-python-cookies-to-a-file – gtalarico Jun 29 '15 at 23:35