From 14f1d0853bd633deadda2b7fcd3121615ca78a8f Mon Sep 17 00:00:00 2001 From: barshaul Date: Tue, 9 Jul 2024 12:09:20 +0000 Subject: [PATCH] addressed comments Signed-off-by: barshaul --- examples/python/cluster_example.py | 70 ++++++++++++++++++++++----- examples/python/standalone_example.py | 68 +++++++++++++++++++++----- python/README.md | 3 +- 3 files changed, 115 insertions(+), 26 deletions(-) diff --git a/examples/python/cluster_example.py b/examples/python/cluster_example.py index e3022ca7af..58a795b54c 100644 --- a/examples/python/cluster_example.py +++ b/examples/python/cluster_example.py @@ -1,4 +1,5 @@ import asyncio +from typing import List, Tuple from glide import ( AllNodes, @@ -14,10 +15,24 @@ async def create_client( - host: str = "localhost", port: int = 6379 + nodes_list: List[Tuple[str, int]] = [("localhost", 47243)] ) -> GlideClusterClient: - # In cluster mode, add the address of any node; the client will automatically discover all nodes in the cluster. - addresses = [NodeAddress(host, port)] + """ + Creates and returns a GlideClusterClient instance. + + This function initializes a GlideClusterClient with the provided list of nodes. + In cluster mode, add the address of any node; the client will automatically + discover all nodes in the cluster. + + + Args: + nodes_list (List[Tuple[str, int]]): A list of tuples where each tuple + contains a host (str) and port (int). Defaults to [("localhost", 6379)]. + + Returns: + GlideClusterClient: An instance of GlideClusterClient connected to the specified nodes. + """ + addresses = [NodeAddress(host, port) for host, port in nodes_list] # Check `GlideClusterClientConfiguration` for additional options. config = GlideClusterClientConfiguration( addresses=addresses, @@ -29,21 +44,38 @@ async def create_client( async def app_logic(client: GlideClusterClient): + """ + Executes the main logic of the application, performing basic operations + such as SET, GET, PING, and INFO REPLICATION using the provided GlideClusterClient. + + Args: + client (GlideClusterClient): An instance of GlideClusterClient. + """ # Send SET and GET set_response = await client.set("foo", "bar") - print(f"Set response is = {set_response!r}") + Logger.log(LogLevel.INFO, "app", f"Set response is = {set_response!r}") + get_response = await client.get("foo") assert isinstance(get_response, bytes) - print(f"Get response is = {get_response.decode()!r}") + Logger.log(LogLevel.INFO, "app", f"Get response is = {get_response.decode()!r}") + # Send PING to all primaries (according to Redis's PING request_policy) pong = await client.ping() - print(f"PONG response is = {pong}") + Logger.log(LogLevel.INFO, "app", f"PING response is = {pong}") + # Send INFO REPLICATION with routing option to all nodes info_repl_resps = await client.info([InfoSection.REPLICATION], AllNodes()) - print(f"INFO REPLICATION responses from all nodes are=\n{info_repl_resps!r}") + Logger.log( + LogLevel.INFO, + "app", + f"INFO REPLICATION responses from all nodes are=\n{info_repl_resps!r}", + ) async def exec_app_logic(): + """ + Executes the application logic with exception handling. + """ while True: try: client = await create_client() @@ -54,20 +86,32 @@ async def exec_app_logic(): # If the error message contains "NOAUTH", raise the exception # because it indicates a critical authentication issue. if "NOAUTH" in str(e): + Logger.log( + LogLevel.ERROR, + "glide", + f"Authentication error encountered: {e}", + ) raise e - print(f"Client has closed and needs to be re-created: {e}") + Logger.log( + LogLevel.WARN, + "glide", + f"Client has closed and needs to be re-created: {e}", + ) except RequestError as e: - print(f"RequestError encountered: {e}") + Logger.log(LogLevel.ERROR, "glide", f"RequestError encountered: {e}") raise e except Exception as e: - print(f"Unexpected error: {e}") + Logger.log(LogLevel.ERROR, "glide", f"Unexpected error: {e}") raise e finally: try: await client.close() - except Exception: - pass - # Optionally, handle or log closure errors + except Exception as e: + Logger.log( + LogLevel.WARN, + "glide", + f"Error encountered while closing the client: {e}", + ) def main(): diff --git a/examples/python/standalone_example.py b/examples/python/standalone_example.py index d7dd5ec631..7852aa0974 100644 --- a/examples/python/standalone_example.py +++ b/examples/python/standalone_example.py @@ -1,4 +1,5 @@ import asyncio +from typing import List, Tuple from glide import ( ClosingError, @@ -11,9 +12,28 @@ ) -async def create_client(host: str = "localhost", port: int = 6379) -> GlideClient: - # Replicas can be added to the addresses list - addresses = [NodeAddress(host, port)] +async def create_client( + nodes_list: List[Tuple[str, int]] = [("localhost", 6379)] +) -> GlideClient: + """ + Creates and returns a GlideClient instance. + + This function initializes a GlideClient with the provided list of nodes. + The nodes_list can contain either only primary nodes or a mix of primary + and replica nodes. The GlideClient will use these nodes to connect to + the Redis cluster or standalone server. + + Args: + nodes_list (List[Tuple[str, int]]): A list of tuples where each tuple + contains a host (str) and port (int). Defaults to [("localhost", 6379)]. + + Returns: + GlideClient: An instance of GlideClient connected to the specified nodes. + """ + addresses = [] + for host, port in nodes_list: + addresses.append(NodeAddress(host, port)) + # Check `GlideClientConfiguration` for additional options. config = GlideClientConfiguration( addresses, @@ -24,18 +44,30 @@ async def create_client(host: str = "localhost", port: int = 6379) -> GlideClien async def app_logic(client: GlideClient): + """ + Executes the main logic of the application, performing basic operations + such as SET, GET, and PING using the provided GlideClient. + + Args: + client (GlideClient): An instance of GlideClient. + """ # Send SET and GET set_response = await client.set("foo", "bar") - print(f"Set response is = {set_response!r}") + Logger.log(LogLevel.INFO, "app", f"Set response is = {set_response!r}") + get_response = await client.get("foo") assert isinstance(get_response, bytes) - print(f"Get response is = {get_response.decode()!r}") + Logger.log(LogLevel.INFO, "app", f"Get response is = {get_response.decode()!r}") + # Send PING to the primary node pong = await client.ping() - print(f"PONG response is = {pong}") + Logger.log(LogLevel.INFO, "app", f"PING response is = {pong}") async def exec_app_logic(): + """ + Executes the application logic with exception handling. + """ while True: try: client = await create_client() @@ -46,20 +78,32 @@ async def exec_app_logic(): # If the error message contains "NOAUTH", raise the exception # because it indicates a critical authentication issue. if "NOAUTH" in str(e): + Logger.log( + LogLevel.ERROR, + "glide", + f"Authentication error encountered: {e}", + ) raise e - print(f"Client has closed and needs to be re-created: {e}") + Logger.log( + LogLevel.WARN, + "glide", + f"Client has closed and needs to be re-created: {e}", + ) except RequestError as e: - print(f"RequestError encountered: {e}") + Logger.log(LogLevel.ERROR, "glide", f"RequestError encountered: {e}") raise e except Exception as e: - print(f"Unexpected error: {e}") + Logger.log(LogLevel.ERROR, "glide", f"Unexpected error: {e}") raise e finally: try: await client.close() - except Exception: - pass - # Optionally, handle or log closure errors + except Exception as e: + Logger.log( + LogLevel.WARN, + "glide", + f"Encountered an error while closing the client: {e}", + ) def main(): diff --git a/python/README.md b/python/README.md index e1b2954ef7..6f7f8666d4 100644 --- a/python/README.md +++ b/python/README.md @@ -80,7 +80,8 @@ Get response is bar >>> asyncio.run(test_standalone_client()) Set response is OK Get response is bar -``` + +For complete examples, please refer to the [cluster example](https://github.com/valkey-io/valkey-glide/blob/main/examples/python/cluster_example.py) and the [standalone example](https://github.com/valkey-io/valkey-glide/blob/main/examples/python/standalone_example.py). ## Documentation