반응형

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
-------------------------------------------------

반응형

+ Recent posts