Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking for expiration and renewing auth session (pythonic way)
    primarykey
    data
    text
    <p>A complete python newbie here, so don't shout at me :D</p> <p>I'm communicating with an online service and some questions popped up. :)</p> <p>The errors returned by the service are: <code>{"error" : {"code" : 1, "message" : "Descriptive message."}}</code> 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.</p> <p>So this script works, but i don't like the big execution bit at the end.</p> <pre><code>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 </code></pre> <p>Is there a way to do this better?</p> <p>It's possible to move the check and renewal in the function itself. And the execution at the end will be just:</p> <pre><code>try: article = get_article(123) print(article) except MyException as e: print(e) </code></pre> <p>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.</p> <p>Maybe the check can be made into a function (i can't figure out how)?</p> <p>Thanks!</p> <p>P.S. 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 :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload