Merge pull request #266 feature-NEWDWH2021-1209 into develop
This commit is contained in:
commit
142d0fff10
@ -16,4 +16,4 @@ RUN \
|
||||
|
||||
COPY src ./src
|
||||
|
||||
CMD ["gunicorn", "src.main:app", "-w", "1", "-k" ,"uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:80", "--timeout", "300"]
|
||||
CMD ["gunicorn", "src.main:app", "-w", "2", "-k" ,"uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:80", "--timeout", "1200", "--keep-alive", "1200"]
|
||||
|
||||
@ -5,6 +5,7 @@ name = "pypi"
|
||||
|
||||
[scripts]
|
||||
app = "uvicorn src.main:app --reload --no-server-header"
|
||||
"app:local" = "gunicorn src.main:app -w 2 -k uvicorn.workers.UvicornWorker -b 127.0.0.1:8000 --timeout 1200 --keep-alive 1200"
|
||||
|
||||
[packages]
|
||||
fastapi = "==0.*"
|
||||
|
||||
@ -9,7 +9,6 @@ from starlette import status
|
||||
|
||||
from src.depends.auth import verify_session
|
||||
from src.depends.services import get_service
|
||||
from src.error.exceptions import DBException
|
||||
from src.logging.get_logger import get_logger
|
||||
from src.model.internal.session import UserSession
|
||||
from src.model.request.bio import BioModel
|
||||
@ -114,7 +113,7 @@ def _search_bio_data(
|
||||
search_param, limitation=environment.BIO_EXCEL_RESULT_MAX_COUNT)
|
||||
elif download_param.ext == 'csv':
|
||||
search_result_df, query = bio_service.search_download_bio_data(search_param)
|
||||
except DBException as e:
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail={'error': 'db_error', 'message': e.args}
|
||||
|
||||
0
ecs/jskult-webapp/src/core/__init__.py
Normal file
0
ecs/jskult-webapp/src/core/__init__.py
Normal file
12
ecs/jskult-webapp/src/core/task.py
Normal file
12
ecs/jskult-webapp/src/core/task.py
Normal file
@ -0,0 +1,12 @@
|
||||
"""FastAPIサーバーの起動イベントのラッパー"""
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from src.db.tasks import init_db
|
||||
|
||||
|
||||
def create_start_app_handler() -> Callable:
|
||||
def start_app() -> None:
|
||||
init_db()
|
||||
|
||||
return start_app
|
||||
@ -1,8 +1,10 @@
|
||||
from sqlalchemy import (Connection, CursorResult, Engine, NullPool,
|
||||
create_engine, event, exc, text)
|
||||
from sqlalchemy import (CursorResult, Engine, NullPool, create_engine, event,
|
||||
exc, text)
|
||||
from sqlalchemy.engine.url import URL
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.pool import Pool
|
||||
|
||||
from src.db.db_row_generator import DBRowGenerator
|
||||
from src.error.exceptions import DBException
|
||||
from src.logging.get_logger import get_logger
|
||||
from src.system_var import environment
|
||||
@ -24,9 +26,8 @@ def ping_connection(dbapi_connection, connection_record, connection_proxy):
|
||||
cursor.close()
|
||||
|
||||
|
||||
class Database:
|
||||
"""データベース操作クラス"""
|
||||
__connection: Connection = None
|
||||
class DatabaseSession:
|
||||
"""データベースセッション管理クラス"""
|
||||
__engine: Engine = None
|
||||
__host: str = None
|
||||
__port: str = None
|
||||
@ -34,6 +35,7 @@ class Database:
|
||||
__password: str = None
|
||||
__schema: str = None
|
||||
__connection_string: str = None
|
||||
__instance = None
|
||||
|
||||
def __init__(self, username: str, password: str, host: str, port: int, schema: str) -> None:
|
||||
"""このクラスの新たなインスタンスを初期化します
|
||||
@ -71,34 +73,48 @@ class Database:
|
||||
"""インスタンスを取得します
|
||||
|
||||
Returns:
|
||||
Database: DB操作クラスインスタンス
|
||||
DatabaseSession: DB操作クラスインスタンス
|
||||
"""
|
||||
return cls(
|
||||
username=environment.DB_USERNAME,
|
||||
password=environment.DB_PASSWORD,
|
||||
host=environment.DB_HOST,
|
||||
port=environment.DB_PORT,
|
||||
schema=environment.DB_SCHEMA
|
||||
)
|
||||
if cls.__instance is None:
|
||||
cls.__instance = cls(
|
||||
username=environment.DB_USERNAME,
|
||||
password=environment.DB_PASSWORD,
|
||||
host=environment.DB_HOST,
|
||||
port=environment.DB_PORT,
|
||||
schema=environment.DB_SCHEMA
|
||||
)
|
||||
|
||||
@property
|
||||
def connection(self):
|
||||
return cls.__instance
|
||||
|
||||
def create_session(self) -> Session:
|
||||
"""
|
||||
DBの接続を返します。
|
||||
"""
|
||||
return self.__connection
|
||||
|
||||
def connect(self):
|
||||
"""
|
||||
DBに接続します。接続に失敗した場合、リトライします。
|
||||
Raises:
|
||||
DBException: 接続失敗
|
||||
Returns:
|
||||
Session: sqlalchemy.orm.Session
|
||||
"""
|
||||
try:
|
||||
self.__connection = self.__engine.connect()
|
||||
return sessionmaker(autoflush=False, bind=self.__engine)()
|
||||
except Exception as e:
|
||||
raise DBException(e)
|
||||
|
||||
|
||||
class DatabaseClient:
|
||||
|
||||
__session: Session = None
|
||||
|
||||
def __init__(self, session: Session) -> None:
|
||||
self.__session = session
|
||||
|
||||
@property
|
||||
def session(self) -> Session:
|
||||
"""
|
||||
DBのセッションを返します。
|
||||
"""
|
||||
if self.__session is None:
|
||||
raise DBException('DBに接続していません')
|
||||
return self.__session
|
||||
|
||||
def execute_select(self, select_query: str, parameters=None) -> list[dict]:
|
||||
"""SELECTクエリを実行します。
|
||||
|
||||
@ -110,23 +126,20 @@ class Database:
|
||||
DBException: DBエラー
|
||||
|
||||
Returns:
|
||||
list[dict]: カラム名: 値の辞書リスト
|
||||
DBRowGenerator: カラム名: 値の辞書リストを返すジェネレータオブジェクト
|
||||
"""
|
||||
if self.__connection is None:
|
||||
raise DBException('DBに接続していません')
|
||||
|
||||
result = None
|
||||
try:
|
||||
# トランザクションが開始している場合は、トランザクションを引き継ぐ
|
||||
if self.__connection.in_transaction():
|
||||
result = self.__connection.execute(text(select_query), parameters)
|
||||
if self.session.in_transaction():
|
||||
result = self.session.execute(text(select_query), parameters)
|
||||
else:
|
||||
# トランザクションが明示的に開始していない場合は、クエリ単位でトランザクションをbegin-commitする。
|
||||
result = self.__execute_with_transaction(select_query, parameters)
|
||||
except Exception as e:
|
||||
raise DBException(e)
|
||||
|
||||
result_rows = result.mappings().all()
|
||||
result_rows = DBRowGenerator(result.mappings())
|
||||
return result_rows
|
||||
|
||||
def execute(self, query: str, parameters=None) -> CursorResult:
|
||||
@ -142,14 +155,11 @@ class Database:
|
||||
Returns:
|
||||
CursorResult: 取得結果
|
||||
"""
|
||||
if self.__connection is None:
|
||||
raise DBException('DBに接続していません')
|
||||
|
||||
result = None
|
||||
try:
|
||||
# トランザクションが開始している場合は、トランザクションを引き継ぐ
|
||||
if self.__connection.in_transaction():
|
||||
result = self.__connection.execute(text(query), parameters)
|
||||
if self.session.in_transaction():
|
||||
result = self.session.execute(text(query), parameters)
|
||||
else:
|
||||
# トランザクションが明示的に開始していない場合は、クエリ単位でトランザクションをbegin-commitする。
|
||||
result = self.__execute_with_transaction(query, parameters)
|
||||
@ -160,35 +170,34 @@ class Database:
|
||||
|
||||
def begin(self):
|
||||
"""トランザクションを開始します。"""
|
||||
if not self.__connection.in_transaction():
|
||||
self.__connection.begin()
|
||||
if not self.session.in_transaction():
|
||||
self.session.begin()
|
||||
|
||||
def commit(self):
|
||||
"""トランザクションをコミットします"""
|
||||
if self.__connection.in_transaction():
|
||||
self.__connection.commit()
|
||||
if self.session.in_transaction():
|
||||
self.session.commit()
|
||||
|
||||
def rollback(self):
|
||||
"""トランザクションをロールバックします"""
|
||||
if self.__connection.in_transaction():
|
||||
self.__connection.rollback()
|
||||
if self.session.in_transaction():
|
||||
self.session.rollback()
|
||||
|
||||
def disconnect(self):
|
||||
"""DB接続を切断します。"""
|
||||
if self.__connection is not None:
|
||||
self.__connection.close()
|
||||
self.__connection = None
|
||||
self.session.close()
|
||||
self.__session = None
|
||||
|
||||
def to_jst(self):
|
||||
self.execute('SET time_zone = "+9:00"')
|
||||
|
||||
def __execute_with_transaction(self, query: str, parameters: dict):
|
||||
# トランザクションを開始してクエリを実行する
|
||||
with self.__connection.begin():
|
||||
with self.session.begin():
|
||||
try:
|
||||
result = self.__connection.execute(text(query), parameters=parameters)
|
||||
result = self.session.execute(text(query), parameters)
|
||||
except Exception as e:
|
||||
self.__connection.rollback()
|
||||
self.session.rollback()
|
||||
raise e
|
||||
# ここでコミットされる
|
||||
return result
|
||||
|
||||
14
ecs/jskult-webapp/src/db/db_row_generator.py
Normal file
14
ecs/jskult-webapp/src/db/db_row_generator.py
Normal file
@ -0,0 +1,14 @@
|
||||
from sqlalchemy import MappingResult
|
||||
|
||||
|
||||
class DBRowGenerator:
|
||||
"""DBの検索結果を指定行数ごとに返すジェネレータ
|
||||
"""
|
||||
FETCH_MANY_SIZE = 2000
|
||||
|
||||
def __init__(self, mapping_result: MappingResult) -> None:
|
||||
self.mapping_result = mapping_result
|
||||
|
||||
def __iter__(self):
|
||||
yield_per = self.mapping_result.yield_per(self.FETCH_MANY_SIZE)
|
||||
yield from yield_per
|
||||
7
ecs/jskult-webapp/src/db/tasks.py
Normal file
7
ecs/jskult-webapp/src/db/tasks.py
Normal file
@ -0,0 +1,7 @@
|
||||
from src.db.database import DatabaseSession
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
# DB接続モジュールを初期化
|
||||
# 以降、get_instance()で唯一のインスタンスを取得する
|
||||
DatabaseSession.get_instance()
|
||||
@ -34,8 +34,6 @@ def check_session_expired(session: Union[UserSession, None] = Depends(get_curren
|
||||
last_access_time = session.last_access_time
|
||||
last_access_datetime = datetime.datetime.fromtimestamp(last_access_time)
|
||||
session_expired_period = last_access_datetime + datetime.timedelta(minutes=environment.SESSION_EXPIRE_MINUTE)
|
||||
logger.debug(f'last_access_time: {last_access_datetime}')
|
||||
logger.debug(f'session_expired_period: {session_expired_period}')
|
||||
if session_expired_period < datetime.datetime.now():
|
||||
return None
|
||||
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
from starlette.requests import Request
|
||||
|
||||
from src.db.database import Database
|
||||
from src.db.database import DatabaseClient, DatabaseSession
|
||||
|
||||
|
||||
def get_database(request: Request) -> Database:
|
||||
# medaca_routerでDB接続エンジンが初期化される
|
||||
db = getattr(request.app.state, '_db', None)
|
||||
# uvicornのワーカーが起動したタイミングでは、dbがセットされていないので、ここでセットここでセットする
|
||||
if db is None:
|
||||
db = Database.get_instance()
|
||||
setattr(request.app.state, '_db', db)
|
||||
return db
|
||||
def get_database(request: Request) -> DatabaseClient:
|
||||
try:
|
||||
database_session = DatabaseSession.get_instance()
|
||||
session = database_session.create_session()
|
||||
database = DatabaseClient(session)
|
||||
yield database
|
||||
finally:
|
||||
database.disconnect()
|
||||
|
||||
@ -2,13 +2,13 @@ from typing import Callable, Type
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from src.db.database import Database
|
||||
from src.db.database import DatabaseClient
|
||||
from src.depends.database import get_database
|
||||
from src.services.base_service import BaseService
|
||||
|
||||
|
||||
def get_service(Service_type: Type[BaseService]) -> Callable:
|
||||
def get_service(db: Database = Depends(get_database)) -> Type[BaseService]:
|
||||
def get_service(db: DatabaseClient = Depends(get_database)) -> Type[BaseService]:
|
||||
repositories = {key: repository(db) for key, repository in Service_type.REPOSITORIES.items()}
|
||||
clients = {key: client() for key, client in Service_type.CLIENTS.items()}
|
||||
return Service_type(repositories=repositories, clients=clients)
|
||||
|
||||
@ -7,6 +7,7 @@ from starlette import status
|
||||
import src.static as static
|
||||
from src.controller import (bio, bio_download, healthcheck, login, logout,
|
||||
master_mainte, menu, root, ultmarc)
|
||||
from src.core import task
|
||||
from src.error.exception_handler import http_exception_handler
|
||||
from src.error.exceptions import UnexpectedException
|
||||
|
||||
@ -40,3 +41,6 @@ app.add_exception_handler(status.HTTP_403_FORBIDDEN, http_exception_handler)
|
||||
|
||||
# サーバーエラーが発生した場合のハンドラー。HTTPExceptionではハンドリングできないため、個別に設定
|
||||
app.add_exception_handler(UnexpectedException, http_exception_handler)
|
||||
|
||||
# サーバー起動時のイベント
|
||||
app.add_event_handler('startup', task.create_start_app_handler())
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
@ -140,10 +139,6 @@ class JWTToken:
|
||||
# Cognitoのサーバー時間とのズレにより、Issued atクレームの検証に失敗するパターンに対処する
|
||||
options={'verify_iat': False}
|
||||
)
|
||||
# トークン有効期限をログに出力
|
||||
exp = verified_jwt.get('exp')
|
||||
expire_datetime = datetime.datetime.fromtimestamp(exp) if exp else None
|
||||
logger.info(f"トークン有効期限:{expire_datetime}")
|
||||
# 有効期限(exp)が切れた場合、トークンをリフレッシュする
|
||||
except jwt.ExpiredSignatureError:
|
||||
logger.info('IDトークンの有効期限が切れたため、トークンをリフレッシュ')
|
||||
|
||||
@ -29,7 +29,6 @@ class MasterMainteEmpChgInstFunction(metaclass=ABCMeta):
|
||||
def save(self):
|
||||
error_list = []
|
||||
try:
|
||||
self.emp_chginst_repository.connect()
|
||||
self.emp_chginst_repository.to_jst()
|
||||
self.emp_chginst_repository.begin()
|
||||
(result_message, error_list) = self.write_emp_chg_inst_table()
|
||||
@ -40,8 +39,6 @@ class MasterMainteEmpChgInstFunction(metaclass=ABCMeta):
|
||||
except Exception as e:
|
||||
self.emp_chginst_repository.rollback()
|
||||
raise e
|
||||
finally:
|
||||
self.emp_chginst_repository.disconnect()
|
||||
|
||||
return (result_message, error_list)
|
||||
|
||||
|
||||
@ -3,15 +3,15 @@ from abc import ABCMeta
|
||||
import pandas as pd
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.db.database import Database
|
||||
from src.db.database import DatabaseClient
|
||||
from src.model.db.base_db_model import BaseDBModel
|
||||
|
||||
|
||||
class BaseRepository(metaclass=ABCMeta):
|
||||
|
||||
_database: Database
|
||||
_database: DatabaseClient
|
||||
|
||||
def __init__(self, db: Database) -> None:
|
||||
def __init__(self, db: DatabaseClient) -> None:
|
||||
self._database = db
|
||||
|
||||
def fetch_all(self) -> list[BaseDBModel]:
|
||||
@ -36,7 +36,7 @@ class BaseRepository(metaclass=ABCMeta):
|
||||
|
||||
sql_query = pd.read_sql(
|
||||
text(query),
|
||||
con=self._database.connection,
|
||||
con=self._database.session.connection(),
|
||||
params=params)
|
||||
|
||||
df = pd.DataFrame(
|
||||
|
||||
@ -65,25 +65,21 @@ class BioSalesLotRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, parameter: BioModel) -> list[BioSalesLotDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
logger.debug('DB参照実行')
|
||||
where_clause = self.__build_condition(parameter)
|
||||
# システムとしての最大取得件数 +1 まで取る
|
||||
query = self.FETCH_SQL.format(where_clause=where_clause, limit=environment.BIO_SEARCH_RESULT_MAX_COUNT + 1)
|
||||
logger.debug(f'SQL: {query}')
|
||||
result = self._database.execute_select(query, parameter.model_dump())
|
||||
logger.debug(f'count= {len(result)}')
|
||||
models = [BioSalesLotDBModel(**r) for r in result]
|
||||
logger.debug(f'count= {len(models)}')
|
||||
return models
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
def fetch_as_data_frame(self, parameter: BioModel, limitation: int):
|
||||
try:
|
||||
self._database.connect()
|
||||
logger.debug('DB参照実行')
|
||||
where_clause = self.__build_condition(parameter)
|
||||
query = self.FETCH_SQL.format(where_clause=where_clause, limit=limitation)
|
||||
@ -95,8 +91,6 @@ class BioSalesLotRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
def __build_condition(self, parameter: BioModel):
|
||||
where_clauses: list[SQLCondition] = []
|
||||
|
||||
@ -18,7 +18,6 @@ class BuMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_count(self, bu_cd) -> MasterMenteCountModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_COUNT_SQL
|
||||
result = self._database.execute_select(query, {'bu_cd': bu_cd})
|
||||
models = [MasterMenteCountModel(**r) for r in result]
|
||||
@ -28,5 +27,3 @@ class BuMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -11,9 +11,6 @@ logger = get_logger('従業員担当施設マスタ')
|
||||
|
||||
class EmpChgInstRepository(BaseRepository):
|
||||
|
||||
def connect(self):
|
||||
self._database.connect()
|
||||
|
||||
def to_jst(self):
|
||||
self._database.to_jst()
|
||||
|
||||
@ -26,9 +23,6 @@ class EmpChgInstRepository(BaseRepository):
|
||||
def rollback(self):
|
||||
self._database.rollback()
|
||||
|
||||
def disconnect(self):
|
||||
self._database.disconnect()
|
||||
|
||||
INSERT_SQL = """\
|
||||
INSERT INTO {table_name}
|
||||
(
|
||||
@ -147,7 +141,6 @@ class EmpChgInstRepository(BaseRepository):
|
||||
|
||||
def fetch_count(self, inst_cd, ta_cd, start_date, table_name) -> MasterMenteCountModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_COUNT_SQL.format(table_name=table_name)
|
||||
result = self._database.execute_select(query, {'inst_cd': inst_cd, 'ta_cd': ta_cd,
|
||||
'start_date': start_date})
|
||||
@ -158,8 +151,6 @@ class EmpChgInstRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f'DB Error : Exception={e.args}')
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
FETCH_SQL = """\
|
||||
SELECT DISTINCT
|
||||
@ -190,7 +181,6 @@ class EmpChgInstRepository(BaseRepository):
|
||||
|
||||
def fetch_as_data_frame(self, table_name: str, parameter: MasterMainteCsvDlModel):
|
||||
try:
|
||||
self._database.connect()
|
||||
where_clause = self.__build_condition(parameter)
|
||||
query = self.FETCH_SQL.format(table_name=table_name, where_clause=where_clause)
|
||||
logger.debug(f'SQL: {query}')
|
||||
@ -200,8 +190,6 @@ class EmpChgInstRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f'DB Error : Exception={e.args}')
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
def __build_condition(self, parameter: MasterMainteCsvDlModel):
|
||||
where_clauses: list[SQLCondition] = []
|
||||
|
||||
@ -20,7 +20,6 @@ class EmpMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_count(self, emp_cd, start_work_date) -> MasterMenteCountModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_COUNT_SQL
|
||||
result = self._database.execute_select(query, {'emp_cd': emp_cd, 'start_work_date': start_work_date})
|
||||
models = [MasterMenteCountModel(**r) for r in result]
|
||||
@ -30,5 +29,3 @@ class EmpMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -10,7 +10,6 @@ class HdkeTblRepository(BaseRepository):
|
||||
|
||||
def fetch_all(self) -> list[HdkeTblModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query)
|
||||
models = [HdkeTblModel(**r) for r in result]
|
||||
@ -18,5 +17,3 @@ class HdkeTblRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -18,7 +18,6 @@ class InstDivMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_all(self) -> list[InstDivMasterModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
result = self._database.execute_select(self.FETCH_SQL)
|
||||
result_data = [res for res in result]
|
||||
models = [InstDivMasterModel(**r) for r in result_data]
|
||||
@ -26,5 +25,3 @@ class InstDivMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -18,7 +18,6 @@ class MstInstRepository(BaseRepository):
|
||||
|
||||
def fetch_count(self, inst_cd) -> MasterMenteCountModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_COUNT_SQL
|
||||
result = self._database.execute_select(query, {'inst_cd': inst_cd})
|
||||
models = [MasterMenteCountModel(**r) for r in result]
|
||||
@ -28,5 +27,3 @@ class MstInstRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -30,12 +30,9 @@ class PharmacyProductMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_all(self) -> list[PharmacyProductMasterModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
result = self._database.execute_select(self.FETCH_SQL)
|
||||
models = [PharmacyProductMasterModel(**r) for r in result]
|
||||
return models
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -20,7 +20,6 @@ class PrefcMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_all(self) -> list[PrefcMasterModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
result = self._database.execute_select(self.FETCH_SQL)
|
||||
result_data = [res for res in result]
|
||||
models = [PrefcMasterModel(**r) for r in result_data]
|
||||
@ -28,5 +27,3 @@ class PrefcMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -53,7 +53,6 @@ class UltmarcDoctorRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, parameter: UltmarcDoctorSearchModel) -> list[UltmarcDoctorDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
# 文字列の検索を部分一致にするため、モデルをコピー。以降はこのコピーを使用する。
|
||||
clone_parameter = UltmarcDoctorSearchModel(**parameter.model_dump())
|
||||
where_clause = self.__build_condition(clone_parameter)
|
||||
@ -66,8 +65,6 @@ class UltmarcDoctorRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
def __build_condition(self, parameter: UltmarcDoctorSearchModel):
|
||||
where_clauses: list[SQLCondition] = []
|
||||
@ -187,7 +184,6 @@ class UltmarcDoctorRepository(BaseRepository):
|
||||
|
||||
def fetch_one(self, id) -> UltmarcDoctorInfoDBModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_ONE_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcDoctorInfoDBModel(**r) for r in result]
|
||||
@ -197,5 +193,3 @@ class UltmarcDoctorRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -31,7 +31,6 @@ class UltmarcDoctorWrkplaceHisRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> list[UltmarcDoctorWrkplaceHisDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcDoctorWrkplaceHisDBModel(**r) for r in result]
|
||||
@ -41,5 +40,3 @@ class UltmarcDoctorWrkplaceHisRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -30,7 +30,6 @@ class UltmarcDoctorWrkplaceRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> list[UltmarcDoctorWrkplaceDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcDoctorWrkplaceDBModel(**r) for r in result]
|
||||
@ -40,8 +39,6 @@ class UltmarcDoctorWrkplaceRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
FETCH_COUNT_SQL = """\
|
||||
SELECT COUNT(*) AS count
|
||||
@ -51,7 +48,6 @@ class UltmarcDoctorWrkplaceRepository(BaseRepository):
|
||||
|
||||
def fetch_count(self, id) -> UltmarcDoctorWrkplaceCountDBModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_COUNT_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcDoctorWrkplaceCountDBModel(**r) for r in result]
|
||||
@ -61,5 +57,3 @@ class UltmarcDoctorWrkplaceRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -39,7 +39,6 @@ class UltmarcInstRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, parameter: UltmarcInstSearchModel) -> list[UltmarcInstDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
# 文字列の検索を部分一致にするため、モデルをコピー。以降はこのコピーを使用する。
|
||||
clone_parameter = UltmarcInstSearchModel(**parameter.model_dump())
|
||||
where_clause = self.__build_condition(clone_parameter)
|
||||
@ -52,8 +51,6 @@ class UltmarcInstRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
def __build_condition(self, parameter: UltmarcInstSearchModel):
|
||||
where_clauses: list[SQLCondition] = []
|
||||
@ -188,7 +185,6 @@ class UltmarcInstRepository(BaseRepository):
|
||||
|
||||
def fetch_one(self, id) -> UltmarcInstInfoDBModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_ONE_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcInstInfoDBModel(**r) for r in result]
|
||||
@ -198,5 +194,3 @@ class UltmarcInstRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -18,7 +18,6 @@ class UltmarcInstTrtCourseRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> list[UltmarcInstTrtCourseDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
|
||||
@ -29,5 +28,3 @@ class UltmarcInstTrtCourseRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -18,7 +18,6 @@ class UltmarcSosietyRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> list[UltmarcSosietyDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcSosietyDBModel(**r) for r in result]
|
||||
@ -28,5 +27,3 @@ class UltmarcSosietyRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -20,7 +20,6 @@ class UltmarcSpecialistLicenseRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> UltmarcSpecialistLicenseDBModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
models = [UltmarcSpecialistLicenseDBModel(**r) for r in result]
|
||||
@ -30,5 +29,3 @@ class UltmarcSpecialistLicenseRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -18,7 +18,6 @@ class UltmarcDrTrtCourseRepository(BaseRepository):
|
||||
|
||||
def fetch_many(self, id) -> list[UltmarcDrTrtCourseDBModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, {'id': id})
|
||||
|
||||
@ -29,5 +28,3 @@ class UltmarcDrTrtCourseRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e.args}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -17,7 +17,6 @@ class UserMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_one(self, parameter: dict) -> UserMasterModel:
|
||||
try:
|
||||
self._database.connect()
|
||||
query = self.FETCH_SQL
|
||||
result = self._database.execute_select(query, parameter)
|
||||
models = [UserMasterModel(**r) for r in result]
|
||||
@ -27,5 +26,3 @@ class UserMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -31,7 +31,6 @@ class WholesalerMasterRepository(BaseRepository):
|
||||
|
||||
def fetch_all(self) -> list[WholesalerMasterModel]:
|
||||
try:
|
||||
self._database.connect()
|
||||
result = self._database.execute_select(self.FETCH_SQL)
|
||||
result_data = [res for res in result]
|
||||
models = [WholesalerMasterModel(**r) for r in result_data]
|
||||
@ -39,5 +38,3 @@ class WholesalerMasterRepository(BaseRepository):
|
||||
except Exception as e:
|
||||
logger.exception(f"DB Error : Exception={e}")
|
||||
raise e
|
||||
finally:
|
||||
self._database.disconnect()
|
||||
|
||||
@ -5,7 +5,6 @@ from fastapi.exceptions import HTTPException
|
||||
from fastapi.routing import APIRoute
|
||||
from starlette import status
|
||||
|
||||
from src.db.database import Database
|
||||
from src.depends.auth import (check_session_expired, get_current_session,
|
||||
verify_session)
|
||||
from src.error.exceptions import DBException, UnexpectedException
|
||||
@ -78,18 +77,6 @@ class MeDaCaRoute(APIRoute):
|
||||
return response
|
||||
|
||||
|
||||
class PrepareDatabaseRoute(MeDaCaRoute):
|
||||
"""事前処理として、データベースのエンジンを作成するルートハンドラー
|
||||
Args:
|
||||
MeDaCaRoute (MeDaCaRoute): 共通ルートハンドラー
|
||||
"""
|
||||
async def pre_process_route(self, request: Request):
|
||||
request = await super().pre_process_route(request)
|
||||
# DBエンジンを構築して状態にセット
|
||||
request.app.state._db = Database.get_instance()
|
||||
return request
|
||||
|
||||
|
||||
class BeforeCheckSessionRoute(MeDaCaRoute):
|
||||
"""事前処理として、セッションチェックを行うルートハンドラー
|
||||
|
||||
@ -112,12 +99,8 @@ class BeforeCheckSessionRoute(MeDaCaRoute):
|
||||
return session_request
|
||||
|
||||
|
||||
class AfterSetCookieSessionRoute(PrepareDatabaseRoute):
|
||||
"""事後処理として、セッションキーをcookieに設定するカスタムルートハンドラー
|
||||
|
||||
Args:
|
||||
PrepareDatabaseRoute (PrepareDatabaseRoute): DBエンジンセットアップルートハンドラー
|
||||
"""
|
||||
class AfterSetCookieSessionRoute(MeDaCaRoute):
|
||||
"""事後処理として、セッションキーをcookieに設定するカスタムルートハンドラー"""
|
||||
async def post_process_route(self, request: Request, response: Response):
|
||||
response = await super().post_process_route(request, response)
|
||||
session_key = response.headers.get('session_key', None)
|
||||
|
||||
@ -148,7 +148,6 @@ class MasterMainteService(BaseService):
|
||||
|
||||
def copy_data_real_to_dummy(self) -> TableOverrideViewModel:
|
||||
try:
|
||||
self.emp_chginst_repository.connect()
|
||||
self.emp_chginst_repository.to_jst()
|
||||
self.emp_chginst_repository.begin()
|
||||
self.emp_chginst_repository.delete_dummy_table()
|
||||
@ -157,8 +156,6 @@ class MasterMainteService(BaseService):
|
||||
except Exception as e:
|
||||
self.emp_chginst_repository.rollback()
|
||||
raise e
|
||||
finally:
|
||||
self.emp_chginst_repository.disconnect()
|
||||
|
||||
# コピー完了をマークして画面に返却
|
||||
table_override = TableOverrideViewModel(
|
||||
|
||||
@ -200,7 +200,7 @@
|
||||
|
||||
<!-- CSV/Excelダウンロード処理-->
|
||||
<script type="text/javascript">
|
||||
function download(filename, ext) {
|
||||
function download(ext) {
|
||||
// ローディング開始
|
||||
const loading = new Loading();
|
||||
loading.start();
|
||||
@ -243,26 +243,28 @@
|
||||
loading.stop();
|
||||
$(`#modal_${ext}`).modal('toggle');
|
||||
} catch (e) {
|
||||
alert("エラーが発生しました。:" + e.message);
|
||||
// 予期せぬエラーが発生した場合
|
||||
loading.stop();
|
||||
$(`#modal_${ext}`).modal('toggle');
|
||||
$(`#ErrorModal_Unexpected`).modal('toggle');
|
||||
return
|
||||
}
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
loading.stop()
|
||||
const responseJson = jqXHR.responseJSON
|
||||
if (responseJson?.detail?.error === 'db_error') {
|
||||
loading.stop()
|
||||
$(`#modal_${ext}`).modal('toggle');
|
||||
$(`#ErrorModal_DB`).modal('toggle');
|
||||
return
|
||||
}
|
||||
if (responseJson?.detail?.error === 'aws_error') {
|
||||
loading.stop();
|
||||
$(`#modal_${ext}`).modal('toggle');
|
||||
$(`#ErrorModal_AWS`).modal('toggle');
|
||||
$(`#ErrorModal_Unexpected`).modal('toggle');
|
||||
return
|
||||
}
|
||||
|
||||
// 予期せぬエラーが発生した場合
|
||||
loading.stop();
|
||||
$(`#modal_${ext}`).modal('toggle');
|
||||
$(`#ErrorModal_Unexpected`).modal('toggle');
|
||||
return
|
||||
@ -389,7 +391,7 @@
|
||||
'id': 'excel_confirm_ok',
|
||||
'class': 'btn btn-primary',
|
||||
'text': 'OK',
|
||||
'onclick_event': 'download("filename", "xlsx")'
|
||||
'onclick_event': 'download("xlsx")'
|
||||
},
|
||||
{
|
||||
'id': 'excel_confirm_cancel',
|
||||
@ -413,7 +415,7 @@
|
||||
'id': 'csv_confirm_ok',
|
||||
'class': 'btn btn-primary',
|
||||
'text': 'OK',
|
||||
'onclick_event': 'download("filename", "csv")'
|
||||
'onclick_event': 'download("csv")'
|
||||
},
|
||||
{
|
||||
'id': 'csv_confirm_cancel',
|
||||
@ -425,37 +427,19 @@
|
||||
%}
|
||||
{% include '_modal.html' %}
|
||||
{% endwith %}
|
||||
<!-- AWS環境異常エラーモーダル -->
|
||||
{% with
|
||||
modal_id='ErrorModal_AWS',
|
||||
modal_title='エラー',
|
||||
message='AWS環境に異常が発生しました。管理者にお問い合わせください。',
|
||||
icon_key='warning',
|
||||
modal_close_event='location.href="/logout/?reason="',
|
||||
buttons = [
|
||||
{
|
||||
'id': 'error_modal_aws',
|
||||
'class': 'btn btn-primary',
|
||||
'text': 'OK',
|
||||
'onclick_event': 'location.href="/logout/?reason=''"'
|
||||
}
|
||||
]
|
||||
%}
|
||||
{% include '_modal.html' %}
|
||||
{% endwith %}
|
||||
<!-- DB接続失敗エラーモーダル -->
|
||||
{% with
|
||||
modal_id='ErrorModal_DB',
|
||||
modal_title='エラー',
|
||||
message='DB接続に失敗しました。管理者にお問い合わせください。',
|
||||
message='DB接続に失敗しました。しばらく経ってから再度実行してください。',
|
||||
icon_key='warning',
|
||||
modal_close_event='location.href="/logout/?reason="',
|
||||
modal_close_event='',
|
||||
buttons = [
|
||||
{
|
||||
'id': 'error_modal_db',
|
||||
'class': 'btn btn-primary',
|
||||
'text': 'OK',
|
||||
'onclick_event': 'location.href="/logout/?reason=''"'
|
||||
'dismiss': 'modal',
|
||||
'text': 'OK'
|
||||
}
|
||||
]
|
||||
%}
|
||||
@ -466,15 +450,15 @@
|
||||
{% with
|
||||
modal_id='ErrorModal_Unexpected',
|
||||
modal_title='エラー',
|
||||
message='サーバーエラーが発生しました。管理者にお問い合わせください。',
|
||||
message='サーバーからの応答がありません。しばらく経ってから再度実行してください。',
|
||||
icon_key='warning',
|
||||
modal_close_event='location.href="/logout/?reason="',
|
||||
modal_close_event='',
|
||||
buttons = [
|
||||
{
|
||||
'id': 'error_modal_unexpected',
|
||||
'class': 'btn btn-primary',
|
||||
'text': 'OK',
|
||||
'onclick_event': 'location.href="/logout/?reason=''"'
|
||||
'dismiss': 'modal'
|
||||
}
|
||||
]
|
||||
%}
|
||||
|
||||
@ -259,7 +259,7 @@
|
||||
<td class="hpInfoColumn">病床数(定員)</td>
|
||||
<td class="instData"><input type="text" readonly="readonly" value="{{ultmarc.inst_info_data.bed_num or ''}}" class="xSmallTextbox numberBox"></td>
|
||||
<td class="hpInfoColumn captionMenteDate">メンテ年月日</td>
|
||||
<td class="instData menteDate"><input type="text" readonly="readonly" value="{{ultmarc.inst_info_data.prmit_bed_maint_ymd or ''}}" class="menteDateText"></td>
|
||||
<td class="instData menteDate"><input type="text" readonly="readonly" value="{{ultmarc.inst_info_data.prmit_bed_maint_ymd or ''}}" class="menteDateTextbox"></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user