简体   繁体   中英

Checking for expiration and renewing auth session (pythonic way)

A complete python newbie here, so don't shout at me :D

I'm communicating with an online service and some questions popped up. :)

The errors returned by the service are: {"error" : {"code" : 1, "message" : "Descriptive message."}} The sessions last for about 6 hours, so i really want to cache my session and reuse it, because in those 6 hours i can make hundreds of requests and it will be rude to reauth on every one.

So this script works, but i don't like the big execution bit at the end.

import requests

session_file = 'session'
url = 'service.com/articles/get'
api_key = 'my_api_key_goes_here'

class MyException(Exception):
    pass

def load_session(session_file):
    f = open(session_file, 'r')
    session = f.read()
    f.close
    return session

def make_post(session, parameters): 
    post_data = json.dumps({"jsonrpc":"2.0", "session_id":session, "params":parameters})
    return post_data

def get_article(article_id):
    session = load_session(session_file)
    post_data = (session, article_id)
    result = requests.post(url, post_data)
    if 'error' in result:
        raise MyException(result['error'])
    else:
        return result

for attempt in range(2):
    try:
        article = get_article(123)
        print(article)
        break
    except MyException as e:
        if e.args[0]['code'] == 1:
            print('Session expired, renewing')
            login(api_key) #login function omitted for clarity
                           #it also writes the session string to a file
        else:
            print(e) #something else happened (for example 'no such article')
            break
    else:
        break

Is there a way to do this better?

It's possible to move the check and renewal in the function itself. And the execution at the end will be just:

try:
    article = get_article(123)
    print(article)
except MyException as e:
    print(e)

My issue with this is that i have a bunch of other functions that communicate with the api and then i'll have to bloat every one of them with this check.

Maybe the check can be made into a function (i can't figure out how)?

Thanks!

PS In the future i plan to move the functions to another file, and just import them. I also have some questions on this part, but i'll post into a new question later :)

A possible solution that would simplify the process, though it does not exactly answer your specific questions at the end, would be to take advantage of the fact you know that sessions last about 6 hours. Store the time that you logged in with the login(api_key) call along with your session string, and if the current time is > 6 hours from that time, re-login immediately and automatically.

It may work well to include that as a check within your load_session function call.

If the session time is variable, just a lesser length of time that will be sure to renew the session before it does expire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM