FastAPI, SQLAlchemy, MySQL 연동 예제
[참고 동영상(스페인어)] https://youtu.be/2ZXiW1ZQqqU
[소스 Git 링크] https://github.com/pjavier1988/fastapicrud
[models.py]
--------------------------------------
from sqlalchemy import Column, Integer, String
from Connection import Base
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True, index=True)
username = Column(String(20))
fullname = Column(String(200))
role = Column(String(20))
state = Column(Integer)
[schemas.py]
-----------------------------------------------
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
id: Optional[int]
username: str
fullname: str
role: str
state: int
class Config:
orm_mode = True
class UserUpdate(BaseModel):
fullname: str
class Config:
orm_mode = True
class response(BaseModel):
message: str
[Connection.py]
--------------------------------------
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "mysql+mysqlconnector://root:12345@localhost:3306/crudfastapi"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False,autoflush=False,bind=engine)
Base = declarative_base()
[main.py]
--------------------------------------
from typing import List
from fastapi import FastAPI
from fastapi.params import Depends
from starlette.responses import RedirectResponse
import models, schemas
from Connection import SessionLocal, engine
from sqlalchemy.orm import Session
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
@app.get("/")
def main():
return RedirectResponse(url="/docs/")
@app.get('/users/', response_model=List[schemas.User])
def show_users(db: Session=Depends(get_db)):
users = db.query(models.User).all( )
return users
@app.post('/users/', response_model=schemas.User)
def create_users(enter: schemas.User, db: Session=Depends(get_db)):
user = models.User(username = enter.username, fullname=enter.fullname,
role=enter.role, state=enter.state)
db.add(user)
db.commit()
db.refresh(user)
return user
@app.put('/users/{user_id}', response_model=schemas.User)
def update_users(user_id: int, enter: schemas.UserUpdate, db: Session=Depends(get_db)):
user = db.query(models.User).filter_by(id=user_id).first( )
user.fullname=enter.fullname
db.commit()
db.refresh(user)
return user
@app.delete('/users/{user_id}', response_model=schemas.response)
def delete_users(user_id: int, db: Session=Depends(get_db)):
user = db.query(models.User).filter_by(id=user_id).first( )
db.delete(user)
db.commit()
response = schemas.response(message="Successfully removed!")
return response
[requirements.txt] 생략본...
------------------------------------------------
fastapi==0.63.0
mysql==0.0.2
mysql-connector-python-rf==2.2.2
mysqlclient==2.0.3
pydantic==1.7.3
requests==2.25.1
SQLAlchemy==1.3.23
starlette==0.13.6
uvicorn==0.13.3
-------------------------------------------------
'FastAPI' 카테고리의 다른 글
Pydantic 에러 처리 (0) | 2021.12.11 |
---|---|
pydantic 레퍼런스 사이트 (FastAPI 모델 관련) (0) | 2021.12.11 |
FastAPI 기초 예제 (0) | 2021.12.08 |
FastAPI 서버 구축기 (by ssoyyoung ) (0) | 2021.12.04 |
파이썬 웹 프레임워크 FastAPI 공식사이트 (0) | 2021.12.04 |