2

i want to use the login session in another function but it does not work. i use python 2.7 and the requests module. the server is a commercial web api.

def add_device(s, argv):
    headers = {'Content-Type': 'application/json; charset=UTF-8', 'Accept': 'application/json'}
    url = 'https://lvgwatchit01t.***.**/watchit/ui/index.php/wapi/inventory/object?Type=Device'
    s.verify = False
    p = req.Request('PUT', url, json = argv, headers = headers, cookies = sessioncookie).prepare()
    r = s.send(p)
    rc = r.status_code
    print r.text
    return rc


# login routine
s = req.Session()
headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
data = {'username':'***', 'password':'***'}
url = 'https://lvgwatchit01t.***.**/watchit/ui/index.php/user/login'
s.verify = False
p = req.Request('POST', url, data = data, headers = headers).prepare()
r = s.send(p)
parsed_json = json.loads(r.text)
rc = parsed_json['RC']
msg = parsed_json['MSG']
sessioncookie = r.cookies
if rc == "0":
    print msg
    add_device(s, data_add_device)
else:
    print msg
    sys.exit(1)

output:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): lvgwatchit01t.***.**:443
DEBUG:urllib3.connectionpool:https://lvgwatchit01t.***.**:443 "POST /watchit/ui/index.php/user/login HTTP/1.1" 200 106
You were successfully logged in!
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:857: 
DEBUG:urllib3.connectionpool:https://lvgwatchit01t.***.**:443 "PUT /watchit/ui/index.php/wapi/inventory/object?Type=Device HTTP/1.1" 200 1131
{"DATA":...}],"META":{"RC":0,"MSG":"OK"}}

how to get the login session in the second function?

1
  • "commericial api" is a bit vague. Note that many API's have you do the auth part as shown and return a token which you need to add to your headers, but without knowing what API you're using, can't say for certain... but in other words, suggest A) fixing your code to show you took out the broken bit Baurin suggested B) consulting any API documentation your API provides
    – Foon
    Commented Jun 27, 2018 at 12:21

2 Answers 2

2

You pass an argument s but you set the variable again. So you lost the content of the var s and you have to make the request again with the credentials. I think you only need remove the first line of add_device(s, argv)

0
1

after adding the session cookie everything works fine. code updated in initial post.