본문 바로가기
Python/Fast API

[Fast API] 기존 Oracle DB 정보 연동 ORM model 클래스 작성

by ete-llorona 2022. 12. 30.

Fast API 에서 CRUD 작업을 하기 위해서는

1. DB connection 정보 (database.py)
2. DB의 실제 테이블 정보를 담고 있는 model 클래스 (models.py)
3. api에서 입력과 출력 형태를 정의하는 schema 클래스 (schemas.py)
4. 실제 CRUD 작업이 이루어지는 메소드가 구현되어야 한다. (crud.py)

참고: https://fastapi.tiangolo.com/ko/tutorial/sql-databases/

SQL (Relational) Databases - FastAPI

SQL (Relational) Databases Warning The current page still doesn't have a translation for this language. But you can help translating it: Contributing. FastAPI doesn't require you to use a SQL (relational) database. But you can use any relational database t

fastapi.tiangolo.com


새로운 서비스를 Fast API로 구축한다면 모든 정보를 처음부터 기록하는 것이 당연하지만,
이미 구축되어 있는 DB를 기반으로 서비스를 기획할 때는 직접 다 작성하는 게 부담스러울 수 있다.
스키마 정보가 얼마 없다면 직접 작성해도 상관없지만, 수백 수천개가 된다면 model 클래스를 작성하는 데 한참 걸릴 것이다.
다행히 기존 DB 정보에 대해 models.py 를 작성해주는 라이브러리가 있다. sqlacodegen 이다.


1. sqlacodegen 설치

pip install sqlacodegen


pip install 로 sqlacodegen 을 설치한다.



2. models.py 파일 생성

sqlacodegen [해당 데이터베이스 접속정보] > models.py(파일명, 대개 models.py 사용)
sqlacodegen oracle+cx_oracle://{username}:{password}@{hostname}:{port}/{database} > models.py


vscode의 터미널 또는 cmd 창에서 sqlacodegen 데이터베이스 접속 정보 > 파일명 을 입력한다.
앞선 예제에서 oracle 의 접속 정보를 그대로 가져왔지만,
그러면 현재 작업 중인 디렉토리에 models.py 파일이 생성되고,
해당 db의 model 클래스가 기록된다. django 에서의 inspectdb 명령어와 역할이 동일하다.




'Python > Fast API' 카테고리의 다른 글

[Fast API] SQLAlchemy로 Oracle DB 연결하기  (0) 2022.12.28
[Fast API] PyCharm Community - setting  (0) 2022.12.26

댓글