-
Notifications
You must be signed in to change notification settings - Fork 1
[BAK-10] DB 연결 마법사 구현 #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
4a0cf80
27a9b99
ad8d138
aa32a8d
bede728
57c1092
e8694a5
59256f9
929b567
8adb031
5dd1832
26b9c64
a589add
8283e13
65b9a52
36fb86b
0d1a86f
d4475db
1450d66
2170ad9
c0e7651
c63189a
4c3b761
e3fbb4b
a5d622a
4b3927b
5fa9358
2250308
a988e61
21bf04f
6120bc2
aa7d8c1
3252541
c1fc742
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,11 @@ | ||
| from fastapi import APIRouter | ||
|
|
||
| from app.api import test_api | ||
| from app.api import driver_api, test_api | ||
|
|
||
| api_router = APIRouter() | ||
|
|
||
| # 테스트 라우터 | ||
| api_router.include_router(test_api.router, prefix="/test", tags=["Test"]) | ||
|
|
||
| # 라우터 | ||
| # api_router.include_router(connect_driver.router, prefix="/connections", tags=["Driver"]) | ||
| api_router.include_router(driver_api.router, prefix="/connections", tags=["Driver"]) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # app/api/driver_api.py | ||
|
|
||
| from fastapi import APIRouter | ||
|
|
||
| from app.core.db_driver_enum import DBTypesEnum | ||
| from app.core.exceptions import APIException | ||
| from app.core.status import CommonCode | ||
| from app.schemas.driver_info import DriverInfo | ||
| from app.schemas.response import ResponseMessage | ||
| from app.services.driver_service import db_driver_info | ||
|
|
||
| router = APIRouter() | ||
|
|
||
|
|
||
| @router.get("/drivers/{driverId}", response_model=ResponseMessage[DriverInfo], summary="DB 드라이버 정보 조회 API") | ||
| def read_driver_info(driverId: str): | ||
| """DB 드라이버 정보 조회""" | ||
| try: | ||
| # DBTypesEnum에서 driverID에 맞는 객체를 가져옵니다. | ||
| db_type_enum = DBTypesEnum[driverId.lower()] | ||
| return ResponseMessage.success(value=db_driver_info(DriverInfo.from_enum(db_type_enum))) | ||
| # db_type_enum 유효성 검사 실패 | ||
| except KeyError: | ||
| raise APIException(CommonCode.INVALID_ENUM_VALUE) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # app/core/db_driver_enum.py | ||
| from enum import Enum | ||
|
|
||
|
|
||
| class DBTypesEnum(Enum): | ||
| """지원되는 데이터베이스 드라이버 타입""" | ||
|
|
||
| postgresql = "psycopg2" | ||
| mysql = "mysql.connector" | ||
| sqlite = "sqlite3" | ||
| oracle = "cx_Oracle" | ||
| sqlserver = "pyodbc" | ||
| mariadb = "pymysql" |
This file was deleted.
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 여기에 왜 저렇게 줄바꿈이 여러개 생겼는지 모르겠네요. 참 이상허네. |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
보시는 거와 같이 브라우저 첫 화면 역할입니다. 초기 개발 세팅 후 제거를 안한 흔적이죠.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1,2 수정 및 제거 하였습니다.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
# app/api_router.py
from fastapi import APIRouter
from app.routers import users, items # 가정: items 라우터도 있다고 가정
# 최상위 라우터 객체 생성
api_router = APIRouter()
# 기능별 라우터를 여기에 포함 (이때는 prefix를 사용하지 않음)
api_router.include_router(users.router, prefix="/users")
api_router.include_router(items.router, prefix="/items")
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1,2 확인했습니다. 해당 사항 공부하고 진행하겠습니다. |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
# app/schemas/response.py
from typing import Generic, TypeVar, Optional, Any
from pydantic import BaseModel
# T라는 이름의 제네릭 타입 변수 생성. 어떤 타입이든 될 수 있음을 의미.
T = TypeVar('T')
class ResponseMessage(BaseModel, Generic[T]):
"""공용 응답 모델"""
message: str
data: Optional[T] = None
@classmethod
def success(cls, value: T, msg: str = "성공적으로 불러왔습니다."):
return cls(message=msg, data=value)
@classmethod
def error(cls, e: Exception | None = None, msg: str = "처리 중 오류가 발생했습니다."):
if e:
# 실제 운영 환경에서는 logging 라이브러리 사용을 권장합니다.
print(f"[ERROR] {type(e).__name__}: {e}")
return cls(message=msg, data=None)
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 해당 사항 공부 좀 하고 다시 답변드리겠습니다.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 말씀 주신 그대로 수정하였습니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| # app/schemas/driver_info.py | ||
| from pydantic import BaseModel | ||
|
|
||
| from app.core.db_driver_enum import DBTypesEnum | ||
|
|
||
|
|
||
| class DriverInfo(BaseModel): | ||
| db_type: str | ||
| is_installed: bool | ||
| driver_name: str | None | ||
| driver_version: str | None | ||
| driver_size_bytes: int | None | ||
|
|
||
| def update_from_module(self, version: str | None, size: int | None): | ||
| """ | ||
| 객체 자신의 속성을 직접 업데이트하여 설치된 드라이버 정보를 채웁니다. | ||
| """ | ||
| self.is_installed = True | ||
| self.driver_version = version | ||
| self.driver_size_bytes = size | ||
|
|
||
| return self | ||
|
|
||
| @classmethod | ||
| def from_enum(cls, db_type_enum: DBTypesEnum): | ||
| """ | ||
| DBTypesEnum 객체를 인자로 받아, db_type, driver_name만으로 driverInfo 객체를 생성합니다. | ||
| `is_installed`는 False로 설정됩니다. | ||
| """ | ||
| db_type = db_type_enum.name | ||
| driver_name = db_type_enum.value | ||
| return cls( | ||
| db_type=db_type, | ||
| is_installed=False, | ||
| driver_name=driver_name, | ||
| driver_version=None, | ||
| driver_size_bytes=None, | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # app/service/driver_service.py | ||
| import importlib | ||
| import os | ||
|
|
||
| from app.core.exceptions import APIException | ||
| from app.core.status import CommonCode | ||
| from app.schemas.driver_info import DriverInfo | ||
|
|
||
|
|
||
| def db_driver_info(driver_info: DriverInfo): | ||
| try: | ||
| mod = importlib.import_module(driver_info.driver_name) | ||
| version = getattr(mod, "__version__", None) | ||
| path = getattr(mod.__spec__, "origin", None) | ||
| size = os.path.getsize(path) if path else None | ||
|
|
||
| return driver_info.update_from_module(version, size) | ||
|
|
||
| except (ModuleNotFoundError, AttributeError, OSError): | ||
| raise APIException(CommonCode.FAIL) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enum 이름(db_type) = 값(driver_name) 단일화 성공하였으나,
만약 이 상태에서 app/api/connect_driver.py
def read_driver_info(driverId: str):부분을def read_driver_info(driverId: DBTypesEnum):으로 사용할 경우 오류가 납니다. 왜냐면 enum은 이름과 값이 같아야 유효성 검사를 하기 때문이라고 합니다.