Skip to content

Commit

Permalink
addressed comments
Browse files Browse the repository at this point in the history
  • Loading branch information
barshaul committed Jul 9, 2024
1 parent d20e22b commit 8f7dd7a
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 26 deletions.
70 changes: 57 additions & 13 deletions examples/python/cluster_example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from typing import List, Tuple

from glide import (
AllNodes,
Expand All @@ -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,
Expand All @@ -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()
Expand All @@ -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():
Expand Down
68 changes: 56 additions & 12 deletions examples/python/standalone_example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
from typing import List, Tuple

from glide import (
ClosingError,
Expand All @@ -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,
Expand All @@ -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()
Expand All @@ -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():
Expand Down
3 changes: 2 additions & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,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
Expand Down

0 comments on commit 8f7dd7a

Please sign in to comment.