From e42f6461c09c30e6cdceff10cf197fccdd82a6db Mon Sep 17 00:00:00 2001 From: lucasheld Date: Mon, 1 May 2023 18:40:14 +0200 Subject: [PATCH] feat: implement context manager for UptimeKumaApi class --- uptime_kuma_api/api.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/uptime_kuma_api/api.py b/uptime_kuma_api/api.py index 9a8b3f2..273fdf7 100644 --- a/uptime_kuma_api/api.py +++ b/uptime_kuma_api/api.py @@ -337,6 +337,9 @@ class UptimeKumaApi(object): >>> from uptime_kuma_api import UptimeKumaApi >>> api = UptimeKumaApi('INSERT_URL') >>> api.login('INSERT_USERNAME', 'INSERT_PASSWORD') + { + 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjgyOTU4OTU4fQ.Xb81nuKXeNyE1D_XoQowYgsgZHka-edONdwHmIznJdk' + } Now you can call one of the existing methods of the instance. For example create a new monitor: @@ -354,6 +357,20 @@ class UptimeKumaApi(object): >>> api.disconnect() + With a context manager, the disconnect method is called automatically: + + .. code-block:: python + + from uptime_kuma_api import UptimeKumaApi + + with UptimeKumaApi('INSERT_URL') as api: + api.login('INSERT_USERNAME', 'INSERT_PASSWORD') + api.add_monitor( + type=MonitorType.HTTP, + name="Google", + url="https://google.com" + ) + :param str url: The url to the Uptime Kuma instance. For example ``http://127.0.0.1:3001`` :param float wait_timeout: How many seconds the client should wait for the connection., defaults to 1 :param dict headers: Headers that are passed to the socketio connection, defaults to None @@ -419,6 +436,12 @@ class UptimeKumaApi(object): self.connect() + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.disconnect() + @contextmanager def wait_for_event(self, event: Event) -> None: # 200 * 0.05 seconds = 10 seconds