internal 1.1.29__0-py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. internal/__init__.py +0 -0
  2. internal/base_config.py +77 -0
  3. internal/base_factory.py +256 -0
  4. internal/cache_redis.py +20 -0
  5. internal/common_enum/__init__.py +0 -0
  6. internal/common_enum/car_relation_type.py +8 -0
  7. internal/common_enum/description_type.py +7 -0
  8. internal/common_enum/device_code.py +10 -0
  9. internal/common_enum/event_code.py +41 -0
  10. internal/common_enum/lpr_direction.py +7 -0
  11. internal/common_enum/notify_type.py +9 -0
  12. internal/common_enum/operator_type.py +9 -0
  13. internal/common_enum/order_type.py +6 -0
  14. internal/common_enum/websocket_channel.py +8 -0
  15. internal/const.py +50 -0
  16. internal/database.py +60 -0
  17. internal/exception/__init__.py +0 -0
  18. internal/exception/app_exception.py +101 -0
  19. internal/exception/base_exception.py +13 -0
  20. internal/exception/internal_exception.py +83 -0
  21. internal/ext/__init__.py +0 -0
  22. internal/ext/amazon/__init__.py +0 -0
  23. internal/ext/amazon/aws/__init__.py +24 -0
  24. internal/ext/amazon/aws/const.py +3 -0
  25. internal/http/__init__.py +0 -0
  26. internal/http/requests.py +166 -0
  27. internal/http/responses.py +78 -0
  28. internal/interface/__init__.py +0 -0
  29. internal/interface/base_interface.py +42 -0
  30. internal/middleware/__init__.py +0 -0
  31. internal/middleware/log_request.py +47 -0
  32. internal/model/__init__.py +0 -0
  33. internal/model/base_model.py +135 -0
  34. internal/model/operate.py +82 -0
  35. internal/utils.py +128 -0
  36. internal/validator_utils.py +51 -0
  37. internal-1.1.29.0.dist-info/METADATA +27 -0
  38. internal-1.1.29.0.dist-info/RECORD +39 -0
  39. internal-1.1.29.0.dist-info/WHEEL +4 -0
internal/__init__.py ADDED
File without changes
@@ -0,0 +1,77 @@
1
+ from pydantic_settings import BaseSettings
2
+
3
+
4
+ class BaseConfig(BaseSettings):
5
+ DEBUG: bool = False
6
+ RUN_PORT: int = 5000
7
+ TIME_ZONE: str = "Asia/Taipei"
8
+
9
+ OPEN_API_URL: str = "/openapi.json"
10
+
11
+ LOGGER_REQUEST_ENABLE: bool = True
12
+
13
+ # Request
14
+ REQUEST_VERIFY_SSL: bool = False
15
+ REQUEST_PROXY: str = ''
16
+ REQUEST_RETRY_COUNT: int = 0
17
+ REQUEST_RETRY_DELAY_INITIAL_SECONDS: float = 1.0
18
+ REQUEST_RETRY_DELAY_FACTOR: float = 1.5
19
+ REQUEST_RETRY_DELAY_RANDOM_JITTER_MIN: float = 0.0
20
+ REQUEST_RETRY_DELAY_RANDOM_JITTER_MAX: float = 0.3
21
+ REQUEST_CONN_POOL_TIMEOUT: float = 5.0
22
+ REQUEST_CONN_TIMEOUT: float = 5.0
23
+ REQUEST_WRITE_TIMEOUT: float = 5.0
24
+ RESPONSE_READ_TIMEOUT: float = 10.0
25
+
26
+ # AWS
27
+ AWS_ACCESS_KEY_ID: str = ""
28
+ AWS_SECRET_KEY: str = ""
29
+ AWS_REGION: str = ""
30
+ AWS_PARAMETER_PATH_PREFIX: str = ""
31
+ AWS_LOGGROUP_NAME: str = ""
32
+
33
+ # MongoDB
34
+ DATABASE_HOST: str = ''
35
+ DATABASE_USERNAME: str = ''
36
+ DATABASE_PASSWORD: str = ''
37
+ DATABASE_PORT: int = 27017
38
+ DATABASE_NAME: str = ""
39
+ DATABASE_SSL: bool = False
40
+ DATABASE_SSL_CA_CERTS: str = ""
41
+ DATABASE_SERVER_SELECTION_TIMEOUT_MS: int = 5000
42
+ DATABASE_CONNECT_TIMEOUT_MS: int = 10000
43
+ DATABASE_AUTH_SOURCE: str = 'admin'
44
+
45
+ # Micro Service
46
+ AUTH_BASE_URL: str = "http://auth-service-api:5000"
47
+ ORGANIZATION_BASE_URL: str = "http://organization-service-api:5000"
48
+ CUSTOMER_BASE_URL: str = "http://customer-service-api:5000"
49
+ CAR_BASE_URL: str = "http://car-service-api:5000"
50
+ RELATIONSHIP_MANAGEMENT_BASE_URL: str = "http://relationship-management-service-api:5000"
51
+ TICKET_BASE_URL: str = "http://ticket-service-api:5000"
52
+ NOTIFY_BASE_URL: str = "http://notify-service-api:5000"
53
+ THIRD_PARTY_BASE_URL: str = "http://third-party-service-api:5000"
54
+ SCHEDULER_BASE_URL: str = "http://scheduler-service-api:5000"
55
+ AUTO_DATA_PROCESSING_BASE_URL: str = "http://auto-data-processing-service-api:5000"
56
+
57
+ # Exception Notify
58
+ WEBHOOK_BASE_URL: str = ""
59
+ WEBHOOK_RETRY_COUNT: int = 5
60
+ WEBHOOK_RETRY_DELAY_INITIAL_SECONDS: float = 1.0
61
+ WEBHOOK_RETRY_DELAY_FACTOR: float = 2.0
62
+ WEBHOOK_RETRY_DELAY_RANDOM_JITTER_MIN: float = 0.0
63
+ WEBHOOK_RETRY_DELAY_RANDOM_JITTER_MAX: float = 0.5
64
+
65
+ # Default System Account Password
66
+ SYSTEM_ACCOUNT: str = "cruisys"
67
+ SYSTEM_PASSWORD: str = "cs50951855"
68
+ SYSTEM_BRAND: str = "cruisys"
69
+ SYSTEM_ORGANIZATION_ID: str = "cruisys"
70
+ SYSTEM_NAME: str = "系統"
71
+ SYSTEM_TITLE: str = ""
72
+
73
+ # Redis URL
74
+ REDIS_URL: str = ""
75
+
76
+ class Config:
77
+ case_sensitive = False
@@ -0,0 +1,256 @@
1
+ import logging
2
+ import logging.handlers
3
+ import os
4
+ import traceback
5
+ from abc import ABCMeta, abstractmethod
6
+ from contextlib import asynccontextmanager
7
+ from functools import lru_cache
8
+ from asgi_correlation_id import CorrelationIdMiddleware, CorrelationIdFilter
9
+
10
+ import dotenv
11
+ import watchtower
12
+ from beanie import init_beanie
13
+ from fastapi import FastAPI, status, Request, APIRouter
14
+ from fastapi.exceptions import RequestValidationError
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+
17
+ from . import database, cache_redis
18
+ from .const import LOG_FMT, LOG_FMT_NO_DT, LOG_DT_FMT, DEFAULT_LOGGER_NAME, CORRELATION_ID_HEADER_KEY_NAME
19
+ from .exception.base_exception import InternalBaseException
20
+ from .exception.internal_exception import BadGatewayException, GatewayTimeoutException
21
+ from .ext.amazon import aws
22
+ from .http.requests import send_webhook_message
23
+ from .http.responses import async_response
24
+ from .middleware.log_request import LogRequestMiddleware
25
+ from .utils import update_dict_with_cast
26
+
27
+
28
+ class BaseFactory(metaclass=ABCMeta):
29
+ DEFAULT_APP_NAME = ""
30
+ API_VERSION = "v0.0.0"
31
+
32
+ @abstractmethod
33
+ def init_modules(self, app):
34
+ """
35
+ Each factory should define what modules it wants.
36
+ """
37
+
38
+ @abstractmethod
39
+ async def get_document_model_list(self) -> list:
40
+ """
41
+ Each factory should define what model it wants.
42
+ """
43
+
44
+ async def init_redis(self, app, app_config):
45
+ if app_config.REDIS_URL:
46
+ redis_cache = cache_redis.CacheRedis(app_config.REDIS_URL)
47
+ await redis_cache.connect()
48
+ app.state.redis = redis_cache.client
49
+ app.state.logger.info("Initialization redis done")
50
+ else:
51
+ app.state.logger.info("skip initialization redis")
52
+
53
+ async def init_state_cache(self, app, app_config):
54
+ """
55
+ Each factory should define what model it wants.
56
+ """
57
+ pass
58
+
59
+ async def init_state_scheduler_app(self, app, app_config):
60
+ """
61
+ Each factory should define what model it wants.
62
+ """
63
+ pass
64
+
65
+ async def close_scheduler_app(self, app, app_config):
66
+ """
67
+ Each factory should define what model it wants.
68
+ """
69
+ pass
70
+
71
+ @abstractmethod
72
+ @lru_cache()
73
+ def get_app_config(self):
74
+ """
75
+ Each factory should define what config it wants.
76
+ """
77
+
78
+ def create_app(self, title=None) -> FastAPI:
79
+
80
+ @asynccontextmanager
81
+ async def lifespan(app: FastAPI):
82
+ # code to execute when app is loading
83
+ await mongodb.connect()
84
+ document_model_list = await self.get_document_model_list()
85
+ await init_beanie(database=app.state.db.get_database(), document_models=document_model_list)
86
+ app.state.logger.info("Database connected")
87
+ await self.init_state_cache(app, self.get_app_config())
88
+ app.state.logger.info("Initialization state cache done")
89
+ await self.init_state_scheduler_app(app, self.get_app_config())
90
+ app.state.logger.info("Initialization state scheduler app done")
91
+ await self.init_redis(app, self.get_app_config())
92
+
93
+ yield
94
+ # code to execute when app is shutting down
95
+ await mongodb.close()
96
+ app.state.logger.info("Database disconnected")
97
+ await self.close_scheduler_app(app, self)
98
+ app.state.logger.info("State scheduler closed")
99
+
100
+ if title is None:
101
+ title = self.DEFAULT_APP_NAME
102
+
103
+ if self.get_app_config().DEBUG:
104
+ app = FastAPI(openapi_url=self.get_app_config().OPEN_API_URL, title=title,
105
+ debug=self.get_app_config().DEBUG, version=self.API_VERSION, lifespan=lifespan)
106
+ else:
107
+ app = FastAPI(openapi_url=self.get_app_config().OPEN_API_URL, title=title,
108
+ debug=self.get_app_config().DEBUG, version=self.API_VERSION, lifespan=lifespan, docs_url=None,
109
+ redoc_url=None)
110
+
111
+ self.__load_local_config()
112
+ app.state.config = self.get_app_config()
113
+ self.__setup_main_logger(app, level=logging.DEBUG)
114
+ app.state.aws_session = aws.init_app(app)
115
+ self.__setup_cloud_log(app)
116
+ self.__load_cloud_config(app)
117
+
118
+ # 不重要的middleware請加在這之前
119
+ if self.get_app_config().LOGGER_REQUEST_ENABLE:
120
+ app.add_middleware(LogRequestMiddleware, logger=app.state.logger)
121
+
122
+
123
+ origins = ["*"]
124
+
125
+ app.add_middleware(
126
+ CORSMiddleware,
127
+ allow_origins=origins,
128
+ allow_credentials=True,
129
+ allow_methods=["*"],
130
+ allow_headers=["*"],
131
+ expose_headers=[CORRELATION_ID_HEADER_KEY_NAME]
132
+ )
133
+
134
+ app.add_middleware(
135
+ CorrelationIdMiddleware,
136
+ header_name=CORRELATION_ID_HEADER_KEY_NAME,
137
+ update_request_header=True
138
+ )
139
+
140
+ mongodb = database.MongoDB(self.get_app_config().DATABASE_USERNAME, self.get_app_config().DATABASE_PASSWORD,
141
+ self.get_app_config().DATABASE_HOST, self.get_app_config().DATABASE_PORT,
142
+ self.get_app_config().DATABASE_NAME,
143
+ self.get_app_config().DATABASE_SERVER_SELECTION_TIMEOUT_MS,
144
+ self.get_app_config().DATABASE_CONNECT_TIMEOUT_MS,
145
+ self.get_app_config().DATABASE_AUTH_SOURCE,
146
+ self.get_app_config().DATABASE_SSL, self.get_app_config().DATABASE_SSL_CA_CERTS)
147
+
148
+ app.state.db = mongodb
149
+ app.state.config = self.get_app_config()
150
+ self.__init_modules(app)
151
+ self.__init_builtin_api(app)
152
+
153
+ @app.exception_handler(InternalBaseException)
154
+ async def http_exception_handler(request: Request, exc: InternalBaseException):
155
+ detail = exc.detail
156
+
157
+ if isinstance(exc, BadGatewayException):
158
+ message = f"【{self.DEFAULT_APP_NAME}】Bad gateway, request:{request.__dict__}, exc:{exc}"
159
+ await send_webhook_message(app, message)
160
+ elif isinstance(exc, GatewayTimeoutException):
161
+ message = f"【{self.DEFAULT_APP_NAME}】Gateway timeout, request:{request.__dict__}, exc:{exc}"
162
+ await send_webhook_message(app, message)
163
+
164
+ return await async_response(data=detail.get("data"), code=detail.get("code"), message=detail.get("message"),
165
+ status_code=exc.status_code)
166
+
167
+ @app.exception_handler(RequestValidationError)
168
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
169
+ data = {"detail": exc.errors()}
170
+ if exc.body:
171
+ data["body"] = exc.body
172
+ return await async_response(data=data,
173
+ code="error_unprocessable_entity", message="Validation failed",
174
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)
175
+
176
+ @app.exception_handler(Exception)
177
+ async def http_exception_handler(request: Request, exc: Exception):
178
+ app.state.logger.warn(f"Exception, request:{request.__dict__}, exc:{exc}")
179
+ app.state.logger.warn(traceback.format_exc())
180
+ message = f"【{self.DEFAULT_APP_NAME}】Unprocessed Exception, request:{request.__dict__}, exc:{exc}"
181
+ await send_webhook_message(app, message)
182
+
183
+ return await async_response(code="error_internal_server", message="Internal server error",
184
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
185
+
186
+ return app
187
+
188
+ def __load_local_config(self):
189
+ dotenv.load_dotenv(override=True)
190
+ update_dict_with_cast(self.get_app_config(), os.environ)
191
+
192
+ def __load_cloud_config(self, app):
193
+ if not app.state.aws_session or not self.get_app_config().AWS_PARAMETER_PATH_PREFIX:
194
+ app.state.logger.warn("No AWS session or Parameter Storage configuration, ignore cloud config")
195
+ return
196
+
197
+ cloud_conf = {}
198
+
199
+ params = {
200
+ "Path": self.get_app_config().AWS_PARAMETER_PATH_PREFIX,
201
+ "Recursive": True,
202
+ "WithDecryption": True
203
+ }
204
+
205
+ # AWS only give us 10 parameters per api call
206
+ ssm_client = app.state.aws_session.client("ssm")
207
+ while True:
208
+ result = ssm_client.get_parameters_by_path(**params)
209
+ cloud_conf.update({para["Name"].split("/")[-1]: para["Value"] for para in result["Parameters"]})
210
+ if not result.get("NextToken"):
211
+ break
212
+ params.update({"NextToken": result["NextToken"]})
213
+
214
+ update_dict_with_cast(self.get_app_config(), cloud_conf)
215
+
216
+ def __init_modules(self, app):
217
+ self.init_modules(app)
218
+
219
+ def __setup_main_logger(self, app, logger_name=DEFAULT_LOGGER_NAME, level=logging.INFO):
220
+ logger = self.__setup_logger(app, logger_name, level)
221
+ app.state.logger = logger
222
+
223
+ #
224
+ def __setup_logger(self, app, logger_name, level=logging.INFO):
225
+ logger = logging.getLogger(logger_name)
226
+ logger.setLevel(level)
227
+
228
+ stream_handler = logging.StreamHandler()
229
+ stream_handler.setFormatter(logging.Formatter(fmt=LOG_FMT))
230
+ stream_handler.addFilter(CorrelationIdFilter())
231
+ logger.addHandler(stream_handler)
232
+
233
+ return logger
234
+
235
+ def __setup_cloud_log(self, app):
236
+ if app.state.aws_session and self.get_app_config().AWS_LOGGROUP_NAME:
237
+ logs_client = app.state.aws_session.client("logs")
238
+ watchtower_handler = watchtower.CloudWatchLogHandler(
239
+ log_group_name=self.get_app_config().AWS_LOGGROUP_NAME,
240
+ boto3_client=logs_client, create_log_group=False)
241
+ watchtower_handler.setFormatter(logging.Formatter(fmt=LOG_FMT_NO_DT, datefmt=LOG_DT_FMT))
242
+ watchtower_handler.addFilter(CorrelationIdFilter())
243
+ app.state.logger.addHandler(watchtower_handler)
244
+
245
+ def __init_builtin_api(self, app):
246
+ router = APIRouter(prefix=f"/system", tags=["system"])
247
+
248
+ @router.get('/health')
249
+ async def health():
250
+ return await async_response()
251
+
252
+ @router.get('/hello')
253
+ async def hello():
254
+ return await async_response(data={"API version": app.version})
255
+
256
+ app.include_router(router)
@@ -0,0 +1,20 @@
1
+ import redis.asyncio as redis
2
+
3
+ from motor.motor_asyncio import AsyncIOMotorClient
4
+ from pymongo.errors import ServerSelectionTimeoutError
5
+
6
+ from .exception.internal_exception import RedisInitializeFailureException, RedisConnectFailureException
7
+
8
+
9
+ class CacheRedis:
10
+ def __init__(self, redis_url: str):
11
+ self.client = None
12
+ self.redis_url = redis_url
13
+
14
+ async def connect(self):
15
+ try:
16
+ connection_pool = redis.ConnectionPool.from_url(self.redis_url, decode_responses=True)
17
+ self.client = redis.Redis(connection_pool=connection_pool)
18
+ await self.client.ping()
19
+ except Exception as e:
20
+ raise RedisInitializeFailureException()
File without changes
@@ -0,0 +1,8 @@
1
+ from enum import Enum
2
+
3
+
4
+ class CarRelationTypeEnum(str, Enum):
5
+ OWNER = "owner"
6
+ DRIVER = "driver"
7
+ BUYER = "buyer"
8
+ CLIENT = "client"
@@ -0,0 +1,7 @@
1
+ from enum import Enum
2
+
3
+
4
+ class DescriptionTypeEnum(str, Enum):
5
+ ALERT = "alert"
6
+ TEXT = "text"
7
+ LINE = "line"
@@ -0,0 +1,10 @@
1
+ from enum import Enum
2
+
3
+
4
+ class DeviceCodeEnum(str, Enum):
5
+ DOOR_IN = "door_in"
6
+ DOOR_OUT = "door_out"
7
+ REPAIR_IN = "repair_in"
8
+ REPAIR_OUT = "repair_out"
9
+ DETAIL_IN = "detail_in"
10
+ DETAIL_OUT = "detail_out"
@@ -0,0 +1,41 @@
1
+ from enum import Enum
2
+
3
+
4
+ class EventCodeEnum(str, Enum):
5
+ MANUAL_CANCEL_SERVICE_TICKET = "manual_cancel_service_ticket"
6
+ MANUAL_TRACING_START_SERVICE_TICKET = "manual_tracing_start_service_ticket"
7
+ MANUAL_TRACING_STOP_SERVICE_TICKET = "manual_tracing_stop_service_ticket"
8
+ MANUAL_CREATE_SERVICE_TICKET = "manual_create_service_ticket"
9
+ MANUAL_IMPORT_RESERVATION_SMWS = "manual_import_reservation_smws"
10
+ MANUAL_MODIFY_USER_SERVICE_TICKET = "manual_modify_user_service_ticket"
11
+ MANUAL_MODIFY_ESTIMATED_ARRIVAL_TIME_SERVICE_TICKET = "manual_modify_estimated_arrival_time_service_ticket"
12
+ MANUAL_MODIFY_ESTIMATED_DELIVERY_TIME_SERVICE_TICKET = "manual_modify_estimated_delivery_time_service_ticket"
13
+ MANUAL_DELETE_ESTIMATED_DELIVERY_TIME_SERVICE_TICKET = "manual_delete_estimated_delivery_time_service_ticket"
14
+ MANUAL_BOOKING_MESSAGE_SERVICE_TICKET = "manual_booking_message_service_ticket"
15
+ MANUAL_DELIVERY_MESSAGE_SERVICE_TICKET = "manual_delivery_message_service_ticket"
16
+
17
+ SYSTEM_TRACING_START_SERVICE_TICKET = "system_tracing_start_service_ticket"
18
+ SYSTEM_TRACING_STOP_SERVICE_TICKET = "system_tracing_stop_service_ticket"
19
+
20
+ NOSHOW_SERVICE_TICKET_AUTO_CANCEL = "noshow_service_ticket_auto_cancel"
21
+ IMPORT_RESERVATION_CONFLICT_AUTO_CANCEL = "import_reservation_conflict_auto_cancel"
22
+ BOOKING_REMINDING_SERVICE_TICKET = "booking_reminding_service_ticket"
23
+ TODAY_REPAIR_WORKING_SERVICE_TICKET_AUTO_CLOSED = "today_repair_working_service_ticket_auto_closed"
24
+
25
+ CAR_IN_ESTABLISHED = "car_in_established"
26
+ CAR_IN_RECEPTION = "car_in_reception"
27
+ CAR_IN_WORKING = "car_in_working"
28
+ CAR_IN_DISPATCH = "car_in_dispatch"
29
+ CAR_IN_DETAILING = "car_in_detailing"
30
+ CAR_IN_NO_TICKET = "car_in_no_ticket"
31
+ CAR_OUT_FINISHED = "car_out_finished"
32
+ CAR_OUT_GENERAL = "car_out_general"
33
+ CAR_OUT_NO_SERVE = "car_out_no_serve"
34
+ CAR_OUT_TEST = "car_out_test"
35
+ CAR_OUT_ACC = "car_out_acc"
36
+
37
+ LPR_CHANGE_STATE = "lpr_change_state"
38
+ LPR_CHANGE_POSITION = "lpr_change_position"
39
+
40
+ REPAIR_OVERDUE = "repair_overdue"
41
+ DETAILING_OVERDUE = "detailing_overdue"
@@ -0,0 +1,7 @@
1
+ from enum import Enum
2
+
3
+
4
+ class LPRDirectionEnum(str, Enum):
5
+ IN = "in"
6
+ OUT = "out"
7
+ UNKNOWN = "unknown"
@@ -0,0 +1,9 @@
1
+ from enum import Enum
2
+
3
+
4
+ class NotifyTypeEnum(str, Enum):
5
+ LINE = "line"
6
+ SMS = "sms"
7
+ APP = "app"
8
+ USER_BELL_NOTIFICATION = "user_bell_notification"
9
+ WEBSOCKET = "websocket"
@@ -0,0 +1,9 @@
1
+ from enum import Enum
2
+
3
+
4
+ class OperatorTypeEnum(str, Enum):
5
+ SYSTEM = "system"
6
+ USER = "user"
7
+ CUSTOMER = "customer"
8
+ PROVIDER = "provider"
9
+ CLIENT = "client"
@@ -0,0 +1,6 @@
1
+ from enum import Enum
2
+
3
+
4
+ class OrderTypeEnum(str, Enum):
5
+ ASC = "asc"
6
+ DESC = "desc"
@@ -0,0 +1,8 @@
1
+ from enum import Enum
2
+
3
+
4
+ class WebsocketChannelEnum(str, Enum):
5
+ OVER_ALL = "over_all" # 儀表板
6
+ RECEPTION_CENTER = "reception_center" # 接待中心
7
+ CAR_MOVEMENT = "car_movement" # 車輛動態
8
+ USER_BELL_NOTIFICATION = "user_bell_notification" # 個人小鈴噹
internal/const.py ADDED
@@ -0,0 +1,50 @@
1
+ # -*- coding: UTF-8 -*-
2
+
3
+
4
+ DATE_FMT = "%Y-%m-%d"
5
+ TIME_FMT = "%H:%M"
6
+ DT_FMT = f"{DATE_FMT} {TIME_FMT}:%S"
7
+
8
+ DEFAULT_LOGGER_NAME = "uvicorn"
9
+ LOG_DT_FMT = f"{DT_FMT},%03d"
10
+ LOG_FMT_NO_DT = "[%(levelname)7s][%(correlation_id)s][%(name)s][%(filename)s::%(funcName)s(%(lineno)s)]: %(message)s"
11
+ LOG_FMT = "[%(asctime)s]" + LOG_FMT_NO_DT
12
+
13
+ ARR_EXPORT_SHORT_FMT = "MM/DD HH:mm"
14
+ ARR_DASH_SHORT_FMT = "MM-DD HH:mm"
15
+ ARR_EXPORT_DATE_FMT = "YYYY/MM/DD"
16
+ ARR_EXPORT_DATE_ONLY_FMT = "MM/DD"
17
+ ARR_DATE_FMT = "YYYY-MM-DD"
18
+ ARR_DATE_FMT_NO_DASH = "YYYYMMDD"
19
+ ARR_EXPORT_DATETIME_FMT = "YYYY/MM/DD HH:mm"
20
+ ARR_TIME_FMT = "HH:mm:ss"
21
+ ARR_TIME_ONLY_FMT = "HH:mm"
22
+ ARR_RFC3339_DT_FMT = f"{ARR_DATE_FMT}T{ARR_TIME_FMT}ZZ"
23
+ ARR_DATETIME_FMT_NO_DASH = "YYYYMMDDHHmmss"
24
+ ARR_HUMAN_READ_FMT = f"{ARR_DATE_FMT} {ARR_TIME_FMT}"
25
+ ARR_IMPORT_TS_FMT = "YYYYMMDDHHmmss.SSSSSS"
26
+ ARR_STR_DAY = "day"
27
+
28
+ STR_EMPTY = ""
29
+ STR_SPACE = " "
30
+ STR_DASH = "-"
31
+ STR_UNDERSCORE = "_"
32
+ STR_SLASH = "/"
33
+ STR_COMMA = ","
34
+
35
+ SECONDS_PER_YEAR = 30758400
36
+ SECONDS_PER_DAY = 86400
37
+ SECONDS_PER_MIN = 60
38
+
39
+ DEF_PAGE_NO = 1
40
+ DEF_PAGE_SIZE = 15
41
+ DEF_ORDER_BY = "_id"
42
+
43
+ REDIS_LPR_DATA_LIST_PREFIX = "lpr_data_list"
44
+
45
+ CORRELATION_ID_HEADER_KEY_NAME = "X-Request-ID"
46
+
47
+ SOURCE_SMART_WORKSHOP_IMPORTED_SERVICE_TICKET = 'SmartWorkshopImportedServiceTicket'
48
+ SOURCE_SMART_WORKSHOP_IMPORTED_DMS_DATA = 'SmartWorkshopImportedDMSData'
49
+ SOURCE_WEBHOOK = 'Webhook'
50
+ SOURCE_SMART_WORKSHOP = 'SmartWorkshopManual'
internal/database.py ADDED
@@ -0,0 +1,60 @@
1
+ from motor.motor_asyncio import AsyncIOMotorClient
2
+ from pymongo.errors import ServerSelectionTimeoutError
3
+
4
+ from .exception.internal_exception import DatabaseInitializeFailureException, DatabaseConnectFailureException
5
+
6
+
7
+ class MongoDB:
8
+ def __init__(self, user_name: str, password: str, host: str, port: int, db_name: str, server_selection_timeout: int,
9
+ connection_timeout: int, auth_source: str, ssl: bool = False, ssl_ca_certs: str = None):
10
+ self.client = None
11
+ self.user_name = user_name
12
+ self.password = password
13
+ self.host = host
14
+ self.port = port
15
+ self.db_name = db_name
16
+ self.connection_timeout = connection_timeout
17
+ self.server_selection_timeout = server_selection_timeout
18
+ self.ssl = ssl
19
+ self.ssl_ca_certs = ssl_ca_certs
20
+ self.auth_source = auth_source
21
+
22
+ async def connect(self):
23
+ try:
24
+ db_settings = dict(username=self.user_name, password=self.password, host=self.host, port=self.port,
25
+ connectTimeoutMS=self.connection_timeout,
26
+ serverSelectionTimeoutMS=self.server_selection_timeout, retryWrites=False,
27
+ authSource=self.auth_source)
28
+ if self.ssl:
29
+ db_settings["ssl"] = self.ssl
30
+
31
+ if self.ssl_ca_certs and self.ssl_ca_certs != "":
32
+ db_settings["tlsCAFile"] = self.ssl_ca_certs
33
+
34
+ self.client = AsyncIOMotorClient(**db_settings)
35
+ except ServerSelectionTimeoutError:
36
+ raise DatabaseInitializeFailureException()
37
+
38
+ async def close(self):
39
+ if self.client:
40
+ self.client.close()
41
+
42
+ def get_database(self):
43
+ if not self.client:
44
+ raise DatabaseConnectFailureException()
45
+ return self.client[self.db_name]
46
+
47
+ async def get_mongodb_uri(self) -> str:
48
+ if self.user_name and self.password:
49
+ uri = f"mongodb://{self.user_name}:{self.password}@{self.host}:{self.port}/{self.db_name}"
50
+ else:
51
+ uri = f"mongodb://{self.host}:{self.port}/{self.db_name}"
52
+
53
+ uri += f"?authSource={self.auth_source}&connectTimeoutMS={self.connection_timeout}&serverSelectionTimeoutMS={self.server_selection_timeout}&retryWrites=false"
54
+
55
+ if self.ssl:
56
+ uri += "&ssl=true"
57
+ if self.ssl_ca_certs and self.ssl_ca_certs != "":
58
+ uri += f"&tlsCAFile={self.ssl_ca_certs}"
59
+
60
+ return uri
File without changes