Feat: use Tribe repository in api

This commit is contained in:
Bertrand Benjamin 2022-12-21 14:16:09 +01:00
parent b3bb1f0cc8
commit 5735d344c5

View File

@ -1,15 +1,17 @@
from fastapi import FastAPI, status
from sqlalchemy import create_engine from sqlalchemy import create_engine
from sqlalchemy.orm import clear_mappers, sessionmaker from sqlalchemy.orm import clear_mappers, sessionmaker
import backend.adapters.orm as orm import backend.adapters.orm as orm
from backend.api.model import TribeModel from backend.api.model import TribeModel
from backend.model.tribe import Tribe from backend.model.tribe import Tribe
from fastapi import FastAPI, status from backend.repository.tribe_sqlalchemy_repository import TribeSQLAlchemyRepository
orm.start_mappers() orm.start_mappers()
engine = create_engine("sqlite:///:memory:") engine = create_engine("sqlite:///:memory:")
orm.metadata.create_all(engine) orm.metadata.create_all(engine)
get_session = sessionmaker(bind=engine) session = sessionmaker(bind=engine)()
tribe_repo = TribeSQLAlchemyRepository(session)
app = FastAPI() app = FastAPI()
@ -18,18 +20,21 @@ app = FastAPI()
async def put_tribe(item: TribeModel): async def put_tribe(item: TribeModel):
tribe = Tribe(**item.dict()) tribe = Tribe(**item.dict())
session = get_session() tribe_repo.add(tribe)
session.add(tribe)
session.commit() session.commit()
return tribe.to_dict() return tribe.to_dict()
@app.get("/tribes", response_model=list[TribeModel]) @app.get("/tribes", response_model=list[TribeModel])
async def get_tribes(): async def list_tribes():
tribes = tribe_repo.list()
session = get_session()
tribes = session.query(Tribe).all()
print(tribes[0].__dict__)
return [t.to_dict() for t in tribes] return [t.to_dict() for t in tribes]
@app.get("/tribes/{name}", response_model=TribeModel)
async def get_tribe(name: str):
tribe = tribe_repo.get(name)
return tribe.to_dict()