try/except in loop

Jason Friedman jsf80238 at gmail.com
Fri Nov 27 20:39:49 EST 2020


>
>
>> I'm using the Box API (
>> https://developer.box.com/guides/tooling/sdks/python/).
>> I can get an access token, though it expires after a certain amount of
>> time. My plan is to store the access token on the filesystem and use it
>> until it expires, then fetch a new one. In the example below assume I have
>> an expired access token.
>>
>> # This next line does not throw an error:
>> client.folder('0').get_items()
>>
>> # But iteration does (maybe this is a lazy fetch?)
>> for _ in client.folder('0').get_items():
>>     logger.debug("Using existing access token.")
>>     return access_token
>>
>> # So I use try/except
>> try:
>>     for _ in client.folder('0').get_items():
>>     logger.debug("Using existing access token.")
>>     return access_token
>> except boxsdk.exception.BoxAPIException:
>>     pass # access token invalid, let's get one
>> else:
>>     pass # access token invalid, let's get one
>>
>> # When running the debugger the except clause seems to catch the first
>> throw, but the loop I think continues, throws the error again, and that
>> second throw is not caught.
>>
>
> It would appear that get items is a generator which uses the token exactly
> once when it is first started; subsequent calls to the generator all use
> the same token. You need to test the token; if it fails,
> obtain a new one, then start the loop.
>

# Here's the solution I came up with:
try:
    list(client.folder('0').get_items())
    logger.debug("Using existing access token.")
    return access_token
except boxsdk.exception.BoxAPIException:
    pass # access token invalid, let's get one

# And for those who happen to be using the Box API, this command avoids all
that and is less expensive:
try:
    client.user().get()
    logger.debug("Using existing access token.")
    return access_token
except boxsdk.exception.BoxAPIException:
    pass # access token invalid, let's get one


More information about the Python-list mailing list