1

This is my first question, please bear with me. I am working with an API that authenticates using an access token that expires in 15 minutes, there is no refresh token to use in-lieu of a re-login. So far I have been able to get the access token and insert it into the requests.get call but I cannot seem to get it to renew and am at a loss as to how. All of the work done with this API, and in general, is with Python so I am hoping to keep it in Python throughout and in the same file.

I get a 401 message code once the 15 minutes are up, and code 200 if successful. So far my only ideas are to put it on a timer for renewal but I cannot make heads or tails of stackoverflow posts or the documentation on doing that, have the login running in a separate script and then this script calls the other one for the current header variable (but that still would require a timer), or have it call to redo the login function once it hits a response.status_code != 200.

Example script for getting the access token

import requests, os, json, time, csv
def login (url, payload):
    #this will log into API and get an access token
    auth = requests.post(url, data=payload).json()
    sessionToken = auth["token"]
    sessionTimer = auth["validFor"]
    headers = {'Access-Token': sessionToken}
    return headers
#calling the function to generate the token
if __name__ == '__main__':
    url = "url inserted here"
    u = input("Enter your username: ")
    p = input("Enter your password: ")
    t = input("Enter your tenancy name: ")
    payload = {'username': u, 'password': p, 'tenant': t}
    print("Logging in")
    headers = login(url, payload)
#the actual work as pulled from a csv file
valuables = input("CSV file with filepath: ")
file = open(valuables, 'r', encoding='utf-8')
csvin = csv.reader(file)
for row in csvin:
    try:
        uuidUrl = row[0]
        output_file = row[1]
        response = requests.get(uuidUrl, headers=headers)
        print(response.status_code)
        with open(output_file, 'wb') as fd:
            for chunk in response.iter_content(chunk_size=128):
                fd.write(chunk)
        fd.close()
    except requests.exceptions.RequestException:
        print(output_file,"may have failed")
        login(url, payload)
        continue

I couldn't get it to successfully recognize a if response.status_code != 200: as a way to call back on the login(). I also couldn't seem to get it to exit a while True: loop.

I apologize I cannot give more details on accessing the API for other people to try out. It is non-public

2
  • I notice you call login() at the bottom, but don't assign the result anywhere. You need to reassign headers = login(url, payload)
    – TallChuck
    Commented Sep 20, 2018 at 15:55
  • Thank you for the advice. I added <code>headers = login(url, payload)</code> before calling the csv file and then within the loop trying to call the headers again. Without success, like so: <code>headers = login(url, payload) csvin = csv.reader(file) for row in csvin: try: uuidUrl = row[0] xip_file = row[1] response = requests.get(uuidUrl, headers=headers) status = response.status_code if status == "401": login(url, payload) headers = login(url, payload) response = requests.get(uuidUrl, headers=headers)</code>
    – Whovian
    Commented Sep 21, 2018 at 14:43

1 Answer 1

2

Eventually I was able to figure out the answer to my own question. Posting this for later users. Updated snippet is below.

Short version of the story: requests.status_code was sending back a integer but I made the faulty assumption that it would be a string, thus my internal comparison was no good.

for row in csvin:
    try:
        uuidUrl = row[0]
        xip_file = row[1]
        response = requests.get(uuidUrl, headers=headers)
        status = response.status_code
        print(status)
        if status == 401:
            print(xip_file, "may have failed, loggin back in")
            login(url, payload)
            headers = login(url, payload)
            response = requests.get(uuidUrl, headers=headers)
            with open(xip_file, 'wb') as fd:
                for chunk in response.iter_content(chunk_size=128):
                    fd.write(chunk)
            fd.close()
        else:
            with open(xip_file, 'wb') as fd:
                for chunk in response.iter_content(chunk_size=128):
                    fd.write(chunk)
            fd.close()
    except requests.exceptions.RequestException:
        print(xip_file,"may have failed")
        headers = login(url, payload)
        continue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.