try/except in loop

Bob Gailer bgailer at gmail.com
Fri Nov 27 18:39:26 EST 2020


On Fri, Nov 27, 2020, 6:06 PM Jason Friedman <jsf80238 at gmail.com> wrote:

> 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.

Bob Gailer

>


More information about the Python-list mailing list