updated and cleaned
This commit is contained in:
@@ -1,9 +1,5 @@
|
||||
|
||||
|
||||
class EmailConfig:
|
||||
EMAIL_HOST: str = "10.10.2.34"
|
||||
EMAIL_USERNAME: str = "karatay@mehmetkaratay.com.tr"
|
||||
EMAIL_PASSWORD: str = "system"
|
||||
EMAIL_PORT: int = 587
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Any, Dict, List, Optional
|
||||
from functools import wraps
|
||||
|
||||
# from pymongo.errors import (
|
||||
# ConnectionFailure,
|
||||
# OperationFailure,
|
||||
@@ -22,4 +23,5 @@ def mongo_error_wrapper(func):
|
||||
:return:
|
||||
"""
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
@@ -10,11 +10,13 @@ from Services.MongoService.handlers import mongo_error_wrapper
|
||||
|
||||
class MongoBase:
|
||||
"""Base class for MongoDB connection and operations."""
|
||||
|
||||
collection: Collection = None
|
||||
|
||||
|
||||
class MongoErrorHandler:
|
||||
"""Error handler for MongoDB operations."""
|
||||
|
||||
...
|
||||
|
||||
|
||||
@@ -63,7 +65,6 @@ class MongoFindMixin(MongoBase):
|
||||
|
||||
|
||||
class MongoUpdateMixin(MongoBase):
|
||||
|
||||
"""Mixin for MongoDB update operations."""
|
||||
|
||||
@mongo_error_wrapper
|
||||
@@ -100,9 +101,10 @@ class MongoDeleteMixin(MongoBase):
|
||||
"""Delete multiple documents from the collection."""
|
||||
return self.collection.delete_many(filter_query)
|
||||
|
||||
class MongoAggregateMixin(MongoBase):
|
||||
|
||||
class MongoAggregateMixin(MongoBase):
|
||||
"""Mixin for MongoDB aggregation operations."""
|
||||
|
||||
@mongo_error_wrapper
|
||||
def aggregate(self, collection: Collection, pipeline: List[Dict[str, Any]]):
|
||||
"""Execute an aggregation pipeline on the collection."""
|
||||
@@ -110,7 +112,6 @@ class MongoAggregateMixin(MongoBase):
|
||||
return result
|
||||
|
||||
|
||||
|
||||
class MongoProvider(
|
||||
MongoUpdateMixin,
|
||||
MongoInsertMixin,
|
||||
@@ -124,9 +125,7 @@ class MongoProvider(
|
||||
managing collections based on company UUID and storage reason.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, client: MongoClient, database: str, storage_reason: list[str]
|
||||
):
|
||||
def __init__(self, client: MongoClient, database: str, storage_reason: list[str]):
|
||||
"""Initialize MongoDB actions with client and collection info.
|
||||
|
||||
Args:
|
||||
@@ -172,7 +171,9 @@ class MongoProvider(
|
||||
collection_name = ""
|
||||
for each_storage_reason in storage_name_list:
|
||||
if self.delimiter in str(each_storage_reason):
|
||||
raise ValueError(f"Storage reason cannot contain delimiter : {self.delimiter}")
|
||||
raise ValueError(
|
||||
f"Storage reason cannot contain delimiter : {self.delimiter}"
|
||||
)
|
||||
collection_name += f"{self.delimiter}{each_storage_reason}"
|
||||
collection_name = collection_name[1:]
|
||||
self._collection = self._client[self._database][collection_name]
|
||||
|
||||
@@ -15,6 +15,7 @@ class Credentials(BaseModel):
|
||||
"""
|
||||
Class to store user credentials.
|
||||
"""
|
||||
|
||||
person_id: int
|
||||
person_name: str
|
||||
full_name: Optional[str] = None
|
||||
@@ -24,6 +25,7 @@ class MetaData:
|
||||
"""
|
||||
Class to store metadata for a query.
|
||||
"""
|
||||
|
||||
created: bool = False
|
||||
updated: bool = False
|
||||
|
||||
@@ -43,7 +45,9 @@ class CRUDModel:
|
||||
Args:
|
||||
record_created: Record that created or updated
|
||||
"""
|
||||
if getattr(cls.creds, "person_id", None) and getattr(cls.creds, "person_name", None):
|
||||
if getattr(cls.creds, "person_id", None) and getattr(
|
||||
cls.creds, "person_name", None
|
||||
):
|
||||
record_created.created_by_id = cls.creds.person_id
|
||||
record_created.created_by = cls.creds.person_name
|
||||
return
|
||||
@@ -72,7 +76,8 @@ class CRUDModel:
|
||||
|
||||
# Search for existing record
|
||||
query = db.query(cls).filter(
|
||||
cls.expiry_ends > str(arrow.now()), cls.expiry_starts <= str(arrow.now()),
|
||||
cls.expiry_ends > str(arrow.now()),
|
||||
cls.expiry_starts <= str(arrow.now()),
|
||||
)
|
||||
|
||||
for key, value in kwargs.items():
|
||||
@@ -119,7 +124,7 @@ class CRUDModel:
|
||||
if str(key[-5:]).lower() == "uu_id": # Special handling for UUID fields
|
||||
return True, str(val)
|
||||
|
||||
if key_: # Handle typed fields
|
||||
if key_: # Handle typed fields
|
||||
if key_ == Mapped[int]:
|
||||
return True, int(val)
|
||||
elif key_ == Mapped[bool]:
|
||||
@@ -130,7 +135,7 @@ class CRUDModel:
|
||||
return True, str(arrow.get(str(val)).format("YYYY-MM-DD HH:mm:ss ZZ"))
|
||||
elif key_ == Mapped[str]:
|
||||
return True, str(val)
|
||||
else: # Handle based on Python types
|
||||
else: # Handle based on Python types
|
||||
if isinstance(val, datetime.datetime):
|
||||
return True, str(arrow.get(str(val)).format("YYYY-MM-DD HH:mm:ss ZZ"))
|
||||
elif isinstance(val, bool):
|
||||
@@ -146,20 +151,24 @@ class CRUDModel:
|
||||
|
||||
return False, None
|
||||
|
||||
def get_dict(self, exclude_list: Optional[list[InstrumentedAttribute]] = None) -> Dict[str, Any]:
|
||||
def get_dict(
|
||||
self, exclude_list: Optional[list[InstrumentedAttribute]] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Convert model instance to dictionary with customizable fields.
|
||||
Returns:
|
||||
Dictionary representation of the model
|
||||
Dictionary returns only UUID fields and fields that are not in exclude_list
|
||||
"""
|
||||
return_dict: Dict[str, Any] = {} # Handle default field selection
|
||||
return_dict: Dict[str, Any] = {} # Handle default field selection
|
||||
exclude_list = exclude_list or []
|
||||
exclude_list = [exclude_arg.key for exclude_arg in exclude_list]
|
||||
|
||||
columns_set = set(self.columns)
|
||||
columns_list = set([col for col in list(columns_set) if str(col)[-2:] != "id"])
|
||||
columns_extend = set(col for col in list(columns_set) if str(col)[-5:].lower() == "uu_id")
|
||||
columns_extend = set(
|
||||
col for col in list(columns_set) if str(col)[-5:].lower() == "uu_id"
|
||||
)
|
||||
columns_list = set(columns_list) | set(columns_extend)
|
||||
columns_list = list(set(columns_list) - set(exclude_list))
|
||||
|
||||
@@ -173,7 +182,10 @@ class CRUDModel:
|
||||
|
||||
@classmethod
|
||||
def find_or_create(
|
||||
cls, db: Session, exclude_args: Optional[list[InstrumentedAttribute]] = None, **kwargs
|
||||
cls,
|
||||
db: Session,
|
||||
exclude_args: Optional[list[InstrumentedAttribute]] = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Find an existing record matching the criteria or create a new one.
|
||||
@@ -188,7 +200,8 @@ class CRUDModel:
|
||||
"""
|
||||
# Search for existing record
|
||||
query = db.query(cls).filter(
|
||||
cls.expiry_ends > str(arrow.now()), cls.expiry_starts <= str(arrow.now()),
|
||||
cls.expiry_ends > str(arrow.now()),
|
||||
cls.expiry_starts <= str(arrow.now()),
|
||||
)
|
||||
exclude_args = exclude_args or []
|
||||
exclude_args = [exclude_arg.key for exclude_arg in exclude_args]
|
||||
@@ -231,7 +244,7 @@ class CRUDModel:
|
||||
db.flush()
|
||||
self.meta_data.updated = True
|
||||
except Exception as e:
|
||||
print('Error:', e)
|
||||
print("Error:", e)
|
||||
self.meta_data.updated = False
|
||||
db.rollback()
|
||||
return self
|
||||
|
||||
@@ -8,8 +8,7 @@ from Services.PostgresService.controllers.response_controllers import PostgresRe
|
||||
from Configs.api import ApiConfigs
|
||||
|
||||
|
||||
class ListOptions:
|
||||
...
|
||||
class ListOptions: ...
|
||||
|
||||
|
||||
class PaginationConfig(BaseModel):
|
||||
@@ -164,25 +163,29 @@ class PaginationResult:
|
||||
"Order by fields and order types must have the same length."
|
||||
)
|
||||
order_criteria = zip(self.order_by, self.order_type)
|
||||
print('order_criteria', order_criteria)
|
||||
print("order_criteria", order_criteria)
|
||||
if not self._data.data:
|
||||
return self._core_query
|
||||
|
||||
for field, direction in order_criteria:
|
||||
print('field', field, direction)
|
||||
print("field", field, direction)
|
||||
columns = self._data.data[0].filterable_attributes
|
||||
print('columns', columns)
|
||||
print("columns", columns)
|
||||
if field in columns:
|
||||
if direction.lower().startswith("d"):
|
||||
self._core_query = self._core_query.order_by(
|
||||
desc(
|
||||
getattr(self._core_query.column_descriptions[0]["entity"], field)
|
||||
getattr(
|
||||
self._core_query.column_descriptions[0]["entity"], field
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
self._core_query = self._core_query.order_by(
|
||||
asc(
|
||||
getattr(self._core_query.column_descriptions[0]["entity"], field)
|
||||
getattr(
|
||||
self._core_query.column_descriptions[0]["entity"], field
|
||||
)
|
||||
)
|
||||
)
|
||||
return self._core_query
|
||||
|
||||
Reference in New Issue
Block a user