I am kind of new in python, trying to develop an user interaction with an API.
In this API I have to authenticate first and then with a token received I can do multiple things,
I have a module authfile.py
that returns a cookie which is in a variable
url = "https://172.16.1.77:8089/api"
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Connection': 'close',
}
def auth(self, url, headers):
data = '{"request": {"action":"challenge","user":"apiuser","version":"1.0"}}'
# First send the challenge.
response = requests.post(url, headers=headers, data=data, verify=False)
# Get the challenge into variable.
a = response.json()
b = a['response']
c = b['challenge']
print("This is the challenge number: " + c)
# Getting the challenge with the Password with MD5
e = input("Please enter the Password\n")
user = c+e
h = hashlib.md5(user.encode())
md = h.hexdigest()
print("This is the Token: " + md)
datas = '{"request":{"action":"login", "token":"' + str(md) + '", "url":"' + str(url) + '" , "user": "cdrapi"}}'
#Send the token to get the Cookie
response2 = requests.post(url, headers=headers, data=datas, verify=False)
#Getting the cookie into a variable
global cookie
f = response2.json()
g = f['response']
cookie = g['cookie']
print("This is the Cookie: " +cookie)
return cookie
cookie = auth(url, headers)
So I have another file that I use to apply some changes, it will need to be in a different module since the applychanges()
functions will be called many times
applychanes.py
:
from authfile import url, headers, cookie
import requests
def changes():
while True:
q = (input("Are you sure you would like to apply changes?\nPlease enter only Y for Yes and N for No\n").lower())
if q.lower() not in ("y", "n"):
print("This is not a valid entry")
if q == "y":
postta = '{"request":{"action":"applyChanges", "cookie":"' + str(cookie) + '"}}'
format_to_json = requests.post(url, headers=headers, data=postta, verify=False)
jsonresponse = format_to_json.json()
# Get the response in a variable
presponse = jsonresponse['response']
# Get the status code into a variable
codestatus = jsonresponse['status']
# Print the reponse
print(presponse)
print(codestatus)
print("The changes has been applied")
break
if q == "n":
print("NO changes has been made")
break
else:
continue
return q
When I call the Cookie, the auth file is excecuted again changing the Cookie and the changes will not be applied since the new cookie means a new session**
How do I call a variable preventing to run the function?
On the Main program the auth MUST be excecuted before anything else.