Config and Service initilaized

This commit is contained in:
berkay 2025-01-13 17:22:20 +03:00
parent 11e457ad02
commit c4013943a1
22 changed files with 474 additions and 0 deletions

3
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,34 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="21">
<item index="0" class="java.lang.String" itemvalue="rsa" />
<item index="1" class="java.lang.String" itemvalue="pydantic" />
<item index="2" class="java.lang.String" itemvalue="alembic" />
<item index="3" class="java.lang.String" itemvalue="starlette-context" />
<item index="4" class="java.lang.String" itemvalue="pymongo" />
<item index="5" class="java.lang.String" itemvalue="arrow" />
<item index="6" class="java.lang.String" itemvalue="unidecode" />
<item index="7" class="java.lang.String" itemvalue="python-dotenv" />
<item index="8" class="java.lang.String" itemvalue="psycopg2-binary" />
<item index="9" class="java.lang.String" itemvalue="cryptography" />
<item index="10" class="java.lang.String" itemvalue="requests" />
<item index="11" class="java.lang.String" itemvalue="redis" />
<item index="12" class="java.lang.String" itemvalue="sqlalchemy" />
<item index="13" class="java.lang.String" itemvalue="pandas" />
<item index="14" class="java.lang.String" itemvalue="fastapi" />
<item index="15" class="java.lang.String" itemvalue="Deprecated" />
<item index="16" class="java.lang.String" itemvalue="faker" />
<item index="17" class="java.lang.String" itemvalue="textdistance" />
<item index="18" class="java.lang.String" itemvalue="uvicorn" />
<item index="19" class="java.lang.String" itemvalue="redmail" />
<item index="20" class="java.lang.String" itemvalue="sqlalchemy-mixins" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
.idea/misc.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.10 (hardware-data-lake)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 virtualenv at ~/git-gitea-evyos/wag-managment-api-service-version-3/.venv" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/wag-managment-api-service-version-4.iml" filepath="$PROJECT_DIR$/.idea/wag-managment-api-service-version-4.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/wag-managment-api-service-version-4" vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.12 virtualenv at ~/git-gitea-evyos/wag-managment-api-service-version-3/.venv" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,18 @@
from AllConfigs import HostConfig
class EmailConfig:
EMAIL_HOST: str = HostConfig.EMAIL_HOST
EMAIL_USERNAME: str = "karatay@mehmetkaratay.com.tr"
EMAIL_PASSWORD: str = "system"
EMAIL_PORT: int = 587
EMAIL_SEND: bool = False
@classmethod
def as_dict(cls):
return dict(
host=EmailConfig.EMAIL_HOST,
port=EmailConfig.EMAIL_PORT,
username=EmailConfig.EMAIL_USERNAME,
password=EmailConfig.EMAIL_PASSWORD,
)

View File

@ -0,0 +1,12 @@
from pydantic import BaseModel
from typing import List, Dict, Optional
class EmailSendModel(BaseModel):
subject: str
html: str = ""
receivers: List[str]
text: Optional[str] = ""
cc: Optional[List[str]] = None
bcc: Optional[List[str]] = None
headers: Optional[Dict] = None
attachments: Optional[Dict] = None

View File

@ -0,0 +1,10 @@
from AllConfigs import HostConfig
class MongoConfig:
PASSWORD = "mongo_password"
USER_NAME = "mongo_user"
DATABASE_NAME = "mongo_database"
HOST = HostConfig.MAIN_HOST
PORT = 11777
URL = f"mongodb://{USER_NAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE_NAME}?retryWrites=true&w=majority"

View File

@ -0,0 +1,8 @@
from AllConfigs import HostConfig
class WagRedis:
REDIS_HOST = HostConfig.MAIN_HOST
REDIS_PASSWORD: str = "commercial_redis_password"
REDIS_PORT: int = 11222
REDIS_DB: int = 0

View File

@ -0,0 +1,11 @@
from AllConfigs import HostConfig
class WagDatabase:
HOST: str = HostConfig.MAIN_HOST
PORT: str = "5444"
SQL: str = "postgresql+psycopg2"
USERNAME: str = "berkay_wag_user"
PASSWORD: str = "berkay_wag_user_password"
DATABASE_NAME: str = "wag_database"
DATABASE_URL: str = f"{SQL}://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE_NAME}"

3
AllConfigs/__init__.py Normal file
View File

@ -0,0 +1,3 @@
from .main import HostConfig
__all__ = ["HostConfig"]

3
AllConfigs/main.py Normal file
View File

@ -0,0 +1,3 @@
class HostConfig:
MAIN_HOST = "10.10.2.36" # http://10.10.2.36
EMAIL_HOST = "10.10.2.34" # http://10.10.2.34

View File

@ -0,0 +1,36 @@
from AllConfigs.Email.configs import EmailConfig
from AllConfigs.Email.email_send_model import EmailSendModel
from redmail import EmailSender
email_sender = EmailSender(**EmailConfig.as_dict())
class EmailService:
@classmethod
def send_email(
cls,
params : EmailSendModel
) -> bool:
if not EmailConfig.EMAIL_SEND:
print("Email sending is disabled", params)
return False
try:
email_sender.connect()
receivers = ["karatay@mehmetkaratay.com.tr"]
email_sender.send(
subject=params.subject,
receivers=receivers,
text=params.text + f" : Gonderilen [{str(receivers)}]",
html=params.html,
cc=params.cc,
bcc=params.bcc,
headers=params.headers or {},
attachments=params.attachments or {},
)
return True
except Exception as e:
print(f"Error raised at email send :{e}")
finally:
email_sender.close()
return False

View File

@ -0,0 +1,148 @@
import json
import arrow
from typing import (
Any,
Optional,
List,
Dict,
)
from ApiServiceRedis.Redis.conn import redis_cli
from ApiServiceRedis.Redis.Models.response import RedisResponse
class RedisRow:
key: str | bytes
value: Any
delimiter: str = "*"
expires_at: Optional[str] = None
@classmethod
def merge(cls, set_values: list[str | bytes]):
for key, set_value in enumerate(set_values):
set_value = str(set_value) if isinstance(set_value, bytes) else set_value
cls.key += f"{set_value}" if key == len(set_values) - 1 else f"{set_value}{cls.delimiter}"
cls.key = cls.key.encode()
@classmethod
def regex(cls, list_keys: list[str | bytes]):
search_regex = ""
for key, list_key in enumerate(list_keys):
list_key = list_key.decode() if isinstance(list_key, bytes) else str(list_key)
if key == 0 and list_key:
search_regex += f"{list_key}{cls.delimiter}*"
elif key == len(list_keys) - 1 and list_key:
search_regex += f"*{cls.delimiter}{list_key}"
else:
if list_key:
search_regex += f"*{cls.delimiter}{list_key}{cls.delimiter}*"
return search_regex
@classmethod
def parse(cls):
return cls.key.split(cls.delimiter) if cls.key else []
@classmethod
def feed(cls, value: Any):
cls.value = json.dumps(value)
@classmethod
def modify(cls, add_dict):
value = cls.data or {}
cls.feed({**value, **add_dict})
@classmethod
def remove(cls, key):
value = cls.data or {}
value.pop(key)
cls.feed(value)
@property
def keys(self):
return self.key if isinstance(self.key, str) else self.key.decode()
@property
def redis_key(self):
return self.key if isinstance(self.key, bytes) else self.key.encode()
@property
def data(self):
return json.loads(self.value)
@property
def as_dict(self):
return {
"keys": self.keys,
"value": self.data,
}
class RedisActions:
@classmethod
def get_expiry_time(cls, expiry_kwargs: dict) -> int:
expiry_time = 0
if "days" in expiry_kwargs:
expiry_time += int(expiry_kwargs["days"]) * 24 * 60 * 60
if "hours" in expiry_kwargs:
expiry_time += int(expiry_kwargs["hours"]) * 60 * 60
if "minutes" in expiry_kwargs:
expiry_time += int(expiry_kwargs["minutes"]) * 60
if "seconds" in expiry_kwargs:
expiry_time += int(expiry_kwargs["seconds"])
return expiry_time
@classmethod
def set_json(
cls, list_keys: list[str | bytes], value: Optional[dict | list], expires: Optional[dict] = None
):
redis_row = RedisRow()
redis_row.merge(set_values=list_keys)
redis_row.feed(value)
try:
if expires:
expiry_time = cls.get_expiry_time(expiry_kwargs=expires)
redis_cli.setex(
name=redis_row.redis_key,
time=expiry_time,
value=redis_row.value,
)
redis_row.expires_at = arrow.now().shift(seconds=expiry_time).format("YYYY-MM-DD HH:mm:ss")
else:
redis_cli.set(name=redis_row.redis_key, value=redis_row.value)
return RedisResponse(
status=True,
message="Value is set successfully.",
data=redis_row,
)
except Exception as e:
return RedisResponse(
status=False,
message="Value is not set successfully.",
error=str(e),
)
@classmethod
def get_json(cls, list_keys: list[str | bytes]):
try:
redis_row = RedisRow()
json_get = redis_cli.get(redis_row.regex(list_keys=list_keys))
redis_row.key = json_get
if not json_get:
return RedisResponse(
status=False,
message="Value is not get successfully.",
error="Value is not found in the redis.",
)
return RedisResponse(
status=True,
message="Value is get successfully.",
data=json.loads(json_get),
)
except Exception as e:
return RedisResponse(
status=False,
message="Value is not get successfully.",
error=str(e),
)

View File

@ -0,0 +1,32 @@
from typing import Union, Dict, List
from ApiServiceRedis.Redis.Actions.actions import RedisRow
class RedisResponse:
def __init__(
self,
status: bool,
message: str,
data: RedisRow = None,
error: str = None,
):
self.status = status
self.message = message
self.data = data
if isinstance(data, dict):
self.data_type = "dict"
elif isinstance(data, list):
self.data_type = "list"
elif data is None:
self.data_type = None
self.error = error
def as_dict(self):
return {
"status": self.status,
"message": self.message,
"data": self.data,
"dataType": self.data_type,
"error": self.error,
}

View File

@ -0,0 +1,25 @@
from pydantic import BaseModel
class AccessToken(BaseModel):
accessToken: str
userUUID: str
def to_list(self):
return [self.accessToken, self.userUUID]
@property
def count(self):
return 2
@property
def delimiter(self):
return "*"
# access_token_obj = AccessToken.from_dict({
# "accessToken": "token",
# "userUUID": "uuid"
# })
# access_token_obj.to_list()

View File

@ -0,0 +1,29 @@
from redis import Redis
from api_configs import WagRedis
class RedisConn:
def __init__(self):
self.redis = Redis(
host=WagRedis.REDIS_HOST,
password=WagRedis.REDIS_PASSWORD,
port=WagRedis.REDIS_PORT,
db=WagRedis.REDIS_DB,
)
if not self.check_connection():
raise Exception("Connection error")
def check_connection(self):
return self.redis.ping()
def set_connection(self, host, password, port, db):
self.redis = Redis(host=host, password=password, port=port, db=db)
return self.redis
try:
redis_conn = RedisConn()
redis_cli = redis_conn.redis
except Exception as e:
print("Redis Connection Error", e)

View File

@ -0,0 +1,10 @@
from ApiServiceRedis.Redis.Actions.actions import RedisActions
from ApiServiceRedis.Redis.Models.row import AccessToken
redis_cli_actions = RedisActions()
access_object = AccessToken(
accessToken="token",
userUUID="uuid"
)

View File

57
api-docker-compose.yml Normal file
View File

@ -0,0 +1,57 @@
services:
wag_management_auth_service:
container_name: wag_management_auth_service
# restart: on-failure
build:
context: .
dockerfile: ApiServices/AuthService/Dockerfile
ports:
- "1111:41575"
environment:
- PYTHONPATH=/service_app
volumes:
- auth_venv:/service_app/.venv
- auth_logs:/service_app/logs
wag_management_validation_service:
container_name: wag_management_validation_service
# restart: on-failure
build:
context: .
dockerfile: ApiServices/ValidationService/Dockerfile
ports:
- "1113:41575"
environment:
- PYTHONPATH=/service_app
volumes:
- validation_venv:/service_app/.venv
- validation_logs:/service_app/logs
# wag_management_init_service:
# container_name: wag_management_init_service
# build:
# context: .
# dockerfile: service_app_init/Dockerfile
# wag_management_event_service:
# container_name: wag_management_event_service
# # restart: on-failure
# build:
# context: .
# dockerfile: ApiServices/EventService/Dockerfile
# ports:
# - "1112:41575"
# environment:
# - PYTHONPATH=/service_app
# volumes:
# - event_venv:/service_app/.venv
# - event_logs:/service_app/logs
volumes:
auth_venv:
event_venv:
validation_venv:
auth_logs:
event_logs:
validation_logs: