Merge pull request #257 feature-NEWDWH2021-1182-backend into develop

This commit is contained in:
下田雅人 2023-08-23 17:32:49 +09:00
commit 920ae17836
11 changed files with 28 additions and 108 deletions

View File

@ -23,7 +23,7 @@ class S3Client(AWSAPIClient):
'Bucket': bucket_name,
'Key': file_key,
# 別ファイル名に変更するための仕掛け。Unicode文字はquoteでエスケープが必要
'ResponseContentDisposition': f'attachment; filename="{quote(download_filename)}"'
'ResponseContentDisposition': f"attachment; filename*=UTF-8''{quote(download_filename)}"
},
# 有効期限20分
ExpiresIn=1200

View File

@ -1,44 +0,0 @@
from typing import Annotated
from fastapi import APIRouter, File, Form, Request, UploadFile
from src.templates import templates
router = APIRouter()
@router.get('/')
def get_view(request: Request):
return templates.TemplateResponse(
'sample_send_file.html',
{
'request': request
}
)
@router.post('/')
# file.readがCoroutineが返ってくるため、必ずasync関数にする
async def post_view(
# formからファイルを受け取る。formタグにenctype="multipart/form-data"を指定すること)
file: Annotated[UploadFile, File()],
message: str = Form()
):
# ファイルを読み込むCoroutineが取れるため、必ずawaitする
file_bytes = await file.read()
# 閉じとく
await file.close()
# 読み込んだファイルはbytesで返ってくるので、デコードする
file_content = file_bytes.decode()
print(file_content)
try:
return {
# ファイル名
"file_name": file.filename,
# ファイルのバイト数
"file_size": file.size,
# Content-Type
"file_content_type": file.content_type
}
except Exception:
return {'code': 'fail'}

View File

@ -1,21 +0,0 @@
"""FastAPIサーバーの起動・終了イベントのラッパー"""
from typing import Callable
from fastapi import FastAPI
from src.db.tasks import close_db, init_db
def create_start_app_handler(app: FastAPI) -> Callable:
def start_app() -> None:
init_db(app)
return start_app
def create_stop_app_handler(app: FastAPI) -> Callable:
def stop_app() -> None:
close_db(app)
return stop_app

View File

@ -1,4 +1,4 @@
from sqlalchemy import (Connection, CursorResult, Engine, QueuePool,
from sqlalchemy import (Connection, CursorResult, Engine, NullPool,
create_engine, event, exc, text)
from sqlalchemy.engine.url import URL
from sqlalchemy.pool import Pool
@ -63,8 +63,7 @@ class Database:
self.__engine = create_engine(
self.__connection_string,
pool_timeout=5,
poolclass=QueuePool
poolclass=NullPool
)
@classmethod
@ -181,7 +180,7 @@ class Database:
self.__connection = None
def to_jst(self):
self.execute('SET time_zone = "+9:00"')
self.execute('SET time_zone = "+9:00"')
def __execute_with_transaction(self, query: str, parameters: dict):
# トランザクションを開始してクエリを実行する

View File

@ -1,14 +0,0 @@
from fastapi import FastAPI
from src.db.database import Database
def init_db(app: FastAPI) -> None:
# DB接続モジュールを初期化
database = Database.get_instance()
# FastAPI App内で使える変数として追加
app.state._db = database
def close_db(app: FastAPI) -> None:
app.state._db = None

View File

@ -1,17 +1,8 @@
from typing import Callable, Type
from fastapi import Depends
from starlette.requests import Request
from src.db.database import Database
from src.repositories.base_repository import BaseRepository
def get_database(request: Request) -> Database:
# medaca_routerでDB接続エンジンが初期化される
return request.app.state._db
def get_repository(Repo_type: Type[BaseRepository]) -> Callable:
def get_repo(db: Database = Depends(get_database)) -> Type[BaseRepository]:
return Repo_type(db)
return get_repo

View File

@ -7,8 +7,6 @@ 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.controller.sample_send_file import router as sample_router
from src.core import tasks
from src.error.exception_handler import http_exception_handler
from src.error.exceptions import UnexpectedException
@ -36,16 +34,9 @@ app.include_router(master_mainte.router, prefix='/masterMainte')
# ヘルスチェック用のルーター
app.include_router(healthcheck.router, prefix='/healthcheck')
# サンプル実装、ファイル送信ルーター
app.include_router(sample_router, prefix='/sample')
# エラー発生時にログアウト画面に遷移させるハンドラー
app.add_exception_handler(status.HTTP_401_UNAUTHORIZED, http_exception_handler)
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', tasks.create_start_app_handler(app))
app.add_event_handler('shutdown', tasks.create_stop_app_handler(app))

View File

@ -5,6 +5,7 @@ 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
@ -75,6 +76,18 @@ 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):
"""事前処理として、セッションチェックを行うルートハンドラー
@ -97,11 +110,11 @@ class BeforeCheckSessionRoute(MeDaCaRoute):
return session_request
class AfterSetCookieSessionRoute(MeDaCaRoute):
class AfterSetCookieSessionRoute(PrepareDatabaseRoute):
"""事後処理として、セッションキーをcookieに設定するカスタムルートハンドラー
Args:
MeDaCaRoute (MeDaCaRoute): 共通ルートハンドラー
PrepareDatabaseRoute (PrepareDatabaseRoute): DBエンジンセットアップルートハンドラー
"""
async def post_process_route(self, request: Request, response: Response):
response = await super().post_process_route(request, response)

View File

@ -28,7 +28,7 @@
</td>
</tr>
</table>
<form class="_form _border" id="bio_search" name="search" action="/bio/BioSearchList" method="POST">
<form class="_form _border" id="bio_search" name="search" action="/bio/BioSearchList" method="POST" onsubmit="showLoading('_loading_for_other')">
<table class="search_table">
<tbody>
<tr>
@ -482,8 +482,13 @@
{% endwith %}
<!-- ローディング -->
<!-- ダウンロード中 -->
{% with progress_message = '出力中...'%}
{% include '_loading.html' %}
{% endwith %}
<!-- それ以外 -->
{% with progress_message = '', id = '_loading_for_other' %}
{% include '_loading.html' %}
{% endwith %}
</body>
</html>

View File

@ -247,9 +247,9 @@
let td = display_keys.map((key) =>{
let inner_content = data[key];
if(key=='dcf_pcf_dr_cd')
inner_content = `<a href="/ultmarc/docInfo?id=${data['dcf_pcf_dr_cd']}">${data['dcf_pcf_dr_cd'] || ''}</a>`;
inner_content = `<a href="javascript:void(0);" onclick="transitionTo('/ultmarc/docInfo?id=${data['dcf_pcf_dr_cd']}')">${data['dcf_pcf_dr_cd'] || ''}</a>`;
else if(key=='dcf_dsf_inst_cd')
inner_content = `<a href="/ultmarc/instInfo?id=${data['dcf_dsf_inst_cd']}" onclick="OnLinkClick()">${data['form_inst_name_kanji'] || ''}</a>`;
inner_content = `<a href="javascript:void(0);" onclick="transitionWithClearSearchItem('/ultmarc/instInfo?id=${data['dcf_dsf_inst_cd']}')">${data['form_inst_name_kanji'] || ''}</a>`;
else if(key=='use_stop_div')
inner_content = useStopDivCategoryName[inner_content] || '';
return `<td>${inner_content || ''}</td>`