canonical/pylxd

Client singleton

Closed this issue · 2 comments

Can we use LXD client object as singleton pattern, means open it once and use several times? If yes, how to check if connection is lost before doing some api query?

@edgarmarkosov yes, you can use it as a singleton, i.e. open it once and use it many times.

The way to check if it's still active is to try to use it and catch the exception if it occurs:

try:
    cs = client.containers.all()
   #... other work
except pylxd.exceptions.ClientConnectionFailed() as e:
    #... do something with the failed connection
except pylxd.exceptions.LXDAPIException() as e:
    #... do soemthing with a failed API call
except pylxd.exceptions.NotFound as e:
    #... an object wasn't found
except pylxd.exceptions.LXDAPIExtensionNotAvailable() as e:
    #... used something that isn't available in this version of LXD
except pylxd.NotADirectoryError as e:
    #... problem when copying files.
except Exception() as e:
    #... something unknown happened, and you probably can't recover from it

Hope that helps. If so, please could you close the issue.
Many thanks!

Thank you @ajkavanagh for your answer.