auth endpoints added

This commit is contained in:
2025-04-03 14:19:34 +03:00
parent 3583d178e9
commit ee405133be
37 changed files with 976 additions and 570 deletions

View File

@@ -15,7 +15,7 @@ from typing import Union, Dict, List, Optional, Any, TypeVar
from Controllers.Redis.connection import redis_cli
T = TypeVar('T', Dict[str, Any], List[Any])
T = TypeVar("T", Dict[str, Any], List[Any])
class RedisKeyError(Exception):
@@ -277,18 +277,18 @@ class RedisRow:
"""
if not key:
raise RedisKeyError("Cannot set empty key")
# Convert to string for validation
key_str = key.decode() if isinstance(key, bytes) else str(key)
# Validate key length (Redis has a 512MB limit for keys)
if len(key_str) > 512 * 1024 * 1024:
raise RedisKeyError("Key exceeds maximum length of 512MB")
# Validate key format (basic check for invalid characters)
if any(c in key_str for c in ['\n', '\r', '\t', '\0']):
if any(c in key_str for c in ["\n", "\r", "\t", "\0"]):
raise RedisKeyError("Key contains invalid characters")
self.key = key if isinstance(key, bytes) else str(key).encode()
@property

View File

@@ -5,11 +5,12 @@ 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,

View File

@@ -98,9 +98,7 @@ class RedisConn:
err = e
return False
def set_connection(
self, **kwargs
) -> Redis:
def set_connection(self, **kwargs) -> Redis:
"""
Recreate Redis connection with new parameters.

View File

@@ -14,6 +14,7 @@ def example_set_json() -> None:
result = RedisActions.set_json(list_keys=keys, value=data, expires=expiry)
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
@@ -25,11 +26,16 @@ def example_get_json() -> None:
result = RedisActions.get_json(list_keys=keys, limit=5)
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.as_dict if isinstance(row.as_dict, dict) else row.as_dict)
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."""
@@ -37,12 +43,14 @@ def example_delete_key() -> None:
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"
@@ -50,48 +58,53 @@ def example_refresh_ttl() -> None:
result = RedisActions.refresh_ttl(key=key, expires=new_expiry)
print("Refresh TTL:", result.as_dict())
def example_key_exists() -> None:
"""Example of checking if a key exists."""
key = "user:profile:123"
exists = RedisActions.key_exists(key)
print(f"Key {key} exists:", exists)
def example_resolve_expires_at() -> None:
"""Example of resolving expiry time for a key."""
from Controllers.Redis.base import RedisRow
redis_row = RedisRow()
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)
def run_all_examples() -> None:
"""Run all example functions to demonstrate RedisActions functionality."""
print("\n=== Redis Actions Examples ===\n")
print("1. Setting JSON data:")
example_set_json()
print("\n2. Getting JSON data:")
example_get_json()
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("\n6. Refreshing TTL:")
example_refresh_ttl()
print("\n7. Checking key existence:")
example_key_exists()
print("\n8. Resolving expiry time:")
example_resolve_expires_at()
if __name__ == "__main__":
run_all_examples()

View File

@@ -67,7 +67,7 @@ class RedisResponse:
# Process single RedisRow
if isinstance(data, RedisRow):
result = {**main_dict}
if hasattr(data, 'keys') and hasattr(data, 'row'):
if hasattr(data, "keys") and hasattr(data, "row"):
if not isinstance(data.keys, str):
raise ValueError("RedisRow keys must be string type")
result[data.keys] = data.row
@@ -80,7 +80,11 @@ class RedisResponse:
# Handle list of RedisRow objects
rows_dict = {}
for row in data:
if isinstance(row, RedisRow) and hasattr(row, 'keys') and hasattr(row, 'row'):
if (
isinstance(row, RedisRow)
and hasattr(row, "keys")
and hasattr(row, "row")
):
if not isinstance(row.keys, str):
raise ValueError("RedisRow keys must be string type")
rows_dict[row.keys] = row.row
@@ -137,10 +141,10 @@ class RedisResponse:
if isinstance(self.data, list) and self.data:
item = self.data[0]
if isinstance(item, RedisRow) and hasattr(item, 'row'):
if isinstance(item, RedisRow) and hasattr(item, "row"):
return item.row
return item
elif isinstance(self.data, RedisRow) and hasattr(self.data, 'row'):
elif isinstance(self.data, RedisRow) and hasattr(self.data, "row"):
return self.data.row
elif isinstance(self.data, dict):
return self.data
@@ -168,16 +172,16 @@ class RedisResponse:
"success": self.status,
"message": self.message,
}
if self.error:
response["error"] = self.error
if self.data is not None:
if self.data_type == "row" and hasattr(self.data, 'to_dict'):
if self.data_type == "row" and hasattr(self.data, "to_dict"):
response["data"] = self.data.to_dict()
elif self.data_type == "list":
try:
if all(hasattr(item, 'to_dict') for item in self.data):
if all(hasattr(item, "to_dict") for item in self.data):
response["data"] = [item.to_dict() for item in self.data]
else:
response["data"] = self.data
@@ -192,5 +196,5 @@ class RedisResponse:
return {
"success": False,
"message": "Error formatting response",
"error": str(e)
}
"error": str(e),
}