recopytex/backend/api/main.py

41 lines
1.0 KiB
Python
Raw Normal View History

2022-12-21 13:16:09 +00:00
from fastapi import FastAPI, status
2022-12-21 05:53:59 +00:00
from sqlalchemy import create_engine
from sqlalchemy.orm import clear_mappers, sessionmaker
import backend.adapters.orm as orm
from backend.api.model import TribeModel
from backend.model.tribe import Tribe
2022-12-21 13:16:09 +00:00
from backend.repository.tribe_sqlalchemy_repository import TribeSQLAlchemyRepository
2022-12-21 05:53:59 +00:00
orm.start_mappers()
engine = create_engine("sqlite:///:memory:")
orm.metadata.create_all(engine)
2022-12-21 13:16:09 +00:00
session = sessionmaker(bind=engine)()
tribe_repo = TribeSQLAlchemyRepository(session)
2022-12-21 05:53:59 +00:00
app = FastAPI()
@app.put("/tribes", status_code=status.HTTP_201_CREATED, response_model=TribeModel)
async def put_tribe(item: TribeModel):
2022-12-21 05:53:59 +00:00
tribe = Tribe(**item.dict())
2022-12-21 13:16:09 +00:00
tribe_repo.add(tribe)
2022-12-21 05:53:59 +00:00
session.commit()
return tribe.to_dict()
2022-12-21 05:53:59 +00:00
@app.get("/tribes", response_model=list[TribeModel])
2022-12-21 13:16:09 +00:00
async def list_tribes():
tribes = tribe_repo.list()
2022-12-21 05:53:59 +00:00
return [t.to_dict() for t in tribes]
2022-12-21 13:16:09 +00:00
@app.get("/tribes/{name}", response_model=TribeModel)
async def get_tribe(name: str):
tribe = tribe_repo.get(name)
return tribe.to_dict()