updated Postgres Service
This commit is contained in:
@@ -10,10 +10,10 @@ This module provides a class for managing Redis key-value operations with suppor
|
||||
|
||||
import arrow
|
||||
import json
|
||||
|
||||
from connection import redis_cli
|
||||
from typing import Union, Dict, List, Optional, Any, TypeVar
|
||||
|
||||
from Controllers.Redis.connection import redis_cli
|
||||
|
||||
|
||||
T = TypeVar('T', Dict[str, Any], List[Any])
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Configs(BaseSettings):
|
||||
"""
|
||||
MongoDB configuration settings.
|
||||
"""
|
||||
HOST: str = ""
|
||||
PASSWORD: str = ""
|
||||
PORT: int = 0
|
||||
DB: int = 0
|
||||
|
||||
def as_dict(self):
|
||||
return dict(
|
||||
host=self.HOST,
|
||||
password=self.PASSWORD,
|
||||
port=int(self.PORT),
|
||||
db=self.DB,
|
||||
)
|
||||
|
||||
model_config = SettingsConfigDict(env_prefix="REDIS_")
|
||||
|
||||
|
||||
redis_configs = Configs() # singleton instance of the REDIS configuration settings
|
||||
print(redis_configs.as_dict())
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import time
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from redis import Redis, ConnectionError, TimeoutError
|
||||
from typing import Dict, Any
|
||||
from redis import Redis, ConnectionError, TimeoutError, ConnectionPool
|
||||
from Controllers.Redis.config import redis_configs
|
||||
|
||||
|
||||
class RedisConn:
|
||||
@@ -16,18 +17,16 @@ class RedisConn:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
max_retries: int = CONNECTION_RETRIES,
|
||||
):
|
||||
"""
|
||||
Initialize Redis connection with configuration.
|
||||
|
||||
Args:
|
||||
config: Redis connection configuration dictionary. If None, uses WagRedis config.
|
||||
max_retries: Maximum number of connection attempts.
|
||||
"""
|
||||
self.max_retries = max_retries
|
||||
self.config = config or {}
|
||||
self.config = redis_configs.as_dict()
|
||||
self._redis = None
|
||||
self._pool = None
|
||||
|
||||
@@ -72,7 +71,6 @@ class RedisConn:
|
||||
for attempt in range(1, self.max_retries + 1):
|
||||
try:
|
||||
if self._pool is None:
|
||||
from redis import ConnectionPool
|
||||
self._pool = ConnectionPool(**self.config)
|
||||
self._redis = Redis(connection_pool=self._pool)
|
||||
if self.check_connection():
|
||||
@@ -101,7 +99,7 @@ class RedisConn:
|
||||
return False
|
||||
|
||||
def set_connection(
|
||||
self, host: str, password: str, port: int, db: int, **kwargs
|
||||
self, **kwargs
|
||||
) -> Redis:
|
||||
"""
|
||||
Recreate Redis connection with new parameters.
|
||||
@@ -119,10 +117,10 @@ class RedisConn:
|
||||
try:
|
||||
# Update configuration
|
||||
self.config = {
|
||||
"host": host,
|
||||
"password": password,
|
||||
"port": port,
|
||||
"db": db,
|
||||
"host": redis_configs.HOST,
|
||||
"password": redis_configs.PASSWORD,
|
||||
"port": redis_configs.PORT,
|
||||
"db": redis_configs.PORT,
|
||||
"socket_timeout": kwargs.get("socket_timeout", self.DEFAULT_TIMEOUT),
|
||||
"socket_connect_timeout": kwargs.get(
|
||||
"socket_connect_timeout", self.DEFAULT_TIMEOUT
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import arrow
|
||||
|
||||
from typing import Optional, List, Dict, Union, Iterator
|
||||
from response import RedisResponse
|
||||
from connection import redis_cli
|
||||
from base import RedisRow
|
||||
|
||||
from Controllers.Redis.response import RedisResponse
|
||||
from Controllers.Redis.connection import redis_cli
|
||||
from Controllers.Redis.base import RedisRow
|
||||
|
||||
|
||||
class MainConfig:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from typing import Dict, List, Optional
|
||||
from database import RedisActions
|
||||
from Controllers.Redis.database import RedisActions
|
||||
|
||||
|
||||
def example_set_json() -> None:
|
||||
"""Example of setting JSON data in Redis with and without expiry."""
|
||||
@@ -7,48 +7,48 @@ def example_set_json() -> None:
|
||||
data = {"name": "John", "age": 30, "city": "New York"}
|
||||
keys = ["user", "profile", "123"]
|
||||
result = RedisActions.set_json(list_keys=keys, value=data)
|
||||
print("Set JSON without expiry:", result)
|
||||
print("Set JSON without expiry:", result.as_dict())
|
||||
|
||||
# Example 2: Set JSON with expiry
|
||||
expiry = {"hours": 1, "minutes": 30}
|
||||
result = RedisActions.set_json(list_keys=keys, value=data, expires=expiry)
|
||||
print("Set JSON with expiry:", result)
|
||||
print("Set JSON with expiry:", result.as_dict())
|
||||
|
||||
def example_get_json() -> None:
|
||||
"""Example of retrieving JSON data from Redis."""
|
||||
# Example 1: Get all matching keys
|
||||
keys = ["user", "profile", "*"]
|
||||
result = RedisActions.get_json(list_keys=keys)
|
||||
print("Get all matching JSON:", result)
|
||||
print("Get all matching JSON:", result.as_dict())
|
||||
|
||||
# Example 2: Get with limit
|
||||
result = RedisActions.get_json(list_keys=keys, limit=5)
|
||||
print("Get JSON with limit:", result)
|
||||
print("Get JSON with limit:", result.as_dict())
|
||||
|
||||
def example_get_json_iterator() -> None:
|
||||
"""Example of using the JSON iterator for large datasets."""
|
||||
keys = ["user", "profile", "*"]
|
||||
for row in RedisActions.get_json_iterator(list_keys=keys):
|
||||
print("Iterating over JSON row:", row)
|
||||
print("Iterating over JSON row:", row.as_dict if isinstance(row.as_dict, dict) else row.as_dict())
|
||||
|
||||
def example_delete_key() -> None:
|
||||
"""Example of deleting a specific key."""
|
||||
key = "user:profile:123"
|
||||
result = RedisActions.delete_key(key)
|
||||
print("Delete specific key:", result)
|
||||
|
||||
def example_delete() -> None:
|
||||
"""Example of deleting multiple keys matching a pattern."""
|
||||
keys = ["user", "profile", "*"]
|
||||
result = RedisActions.delete(list_keys=keys)
|
||||
print("Delete multiple keys:", result)
|
||||
# def example_delete_key() -> None:
|
||||
# """Example of deleting a specific key."""
|
||||
# key = "user:profile:123"
|
||||
# result = RedisActions.delete_key(key)
|
||||
# print("Delete specific key:", result)
|
||||
#
|
||||
# def example_delete() -> None:
|
||||
# """Example of deleting multiple keys matching a pattern."""
|
||||
# keys = ["user", "profile", "*"]
|
||||
# result = RedisActions.delete(list_keys=keys)
|
||||
# print("Delete multiple keys:", result)
|
||||
|
||||
def example_refresh_ttl() -> None:
|
||||
"""Example of refreshing TTL for a key."""
|
||||
key = "user:profile:123"
|
||||
new_expiry = {"hours": 2, "minutes": 0}
|
||||
result = RedisActions.refresh_ttl(key=key, expires=new_expiry)
|
||||
print("Refresh TTL:", result)
|
||||
print("Refresh TTL:", result.as_dict())
|
||||
|
||||
def example_key_exists() -> None:
|
||||
"""Example of checking if a key exists."""
|
||||
@@ -58,9 +58,10 @@ def example_key_exists() -> None:
|
||||
|
||||
def example_resolve_expires_at() -> None:
|
||||
"""Example of resolving expiry time for a key."""
|
||||
from base import RedisRow
|
||||
from Controllers.Redis.base import RedisRow
|
||||
redis_row = RedisRow()
|
||||
redis_row.redis_key = "user:profile:123"
|
||||
redis_row.set_key("user:profile:123")
|
||||
print(redis_row.keys)
|
||||
expires_at = RedisActions.resolve_expires_at(redis_row)
|
||||
print("Resolve expires at:", expires_at)
|
||||
|
||||
@@ -77,11 +78,11 @@ def run_all_examples() -> None:
|
||||
print("\n3. Using JSON iterator:")
|
||||
example_get_json_iterator()
|
||||
|
||||
print("\n4. Deleting specific key:")
|
||||
example_delete_key()
|
||||
|
||||
print("\n5. Deleting multiple keys:")
|
||||
example_delete()
|
||||
# print("\n4. Deleting specific key:")
|
||||
# example_delete_key()
|
||||
#
|
||||
# print("\n5. Deleting multiple keys:")
|
||||
# example_delete()
|
||||
|
||||
print("\n6. Refreshing TTL:")
|
||||
example_refresh_ttl()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from typing import Union, Dict, List, Optional, Any
|
||||
from base import RedisRow
|
||||
from typing import Union, Dict, Optional, Any
|
||||
from Controllers.Redis.base import RedisRow
|
||||
|
||||
|
||||
class RedisResponse:
|
||||
@@ -11,11 +11,11 @@ class RedisResponse:
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
status: bool,
|
||||
message: str,
|
||||
data: Any = None,
|
||||
error: Optional[str] = None,
|
||||
self,
|
||||
status: bool,
|
||||
message: str,
|
||||
data: Any = None,
|
||||
error: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Initialize a Redis response.
|
||||
|
||||
Reference in New Issue
Block a user