python-nomad icon indicating copy to clipboard operation
python-nomad copied to clipboard

Add support for pre-populated Sessions

Open minor-fixes opened this issue 3 years ago • 0 comments

This PR allows the caller to inject a requests.Session object that the Nomad client should use to make all requests, in case the client is used in an environment where cookies/headers/etc. unrelated to Nomad communication must be added to each request.


Tested - both examples below with this change:

Something like this in my environment fails, as it redirects to an auth server: (URLs and other bits changed/redacted below)

import nomad

def main():
    n = nomad.Nomad(host="nomad.corp.example.com", port=443, secure=True, verify=True)
    print("num jobs:", len(n.jobs.get_jobs()))

if __name__ == "__main__":
    main()

prints:

Traceback (most recent call last):
  File "client_test_fail.py", line 8, in <module>
    main()
  File "client_test_fail.py", line 5, in main
    print("num jobs:", len(n.jobs.get_jobs()))
  File "/home/scott/dev/python-nomad/nomad/api/jobs.py", line 84, in get_jobs
    return self.request(method="get", params=params).json()
  File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

whereas preparing and supplying a session:

import requests
import nomad

def main():
    token = "<redacted>"
    s = requests.session()
    s.cookies.set("Creds", token, domain=".corp.example.com")
    with s:
        n = nomad.Nomad(host="nomad.corp.example.com", port=443, secure=True, verify=True, session=s)
        print("num jobs:", len(n.jobs.get_jobs()))

if __name__ == "__main__":
    main()

prints: num jobs: 20

minor-fixes avatar Aug 05 '22 04:08 minor-fixes