generated from daniil-berg/boilerplate-py
44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
from fastapi import FastAPI, HTTPException, Depends
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlmodel import SQLModel
|
|
|
|
from .models import *
|
|
from .models.base import DB
|
|
from . import crud
|
|
|
|
|
|
api, db = FastAPI(), DB()
|
|
|
|
|
|
@api.on_event('startup')
|
|
async def initialize_db():
|
|
async with db.engine.begin() as conn:
|
|
await conn.run_sync(SQLModel.metadata.drop_all)
|
|
await conn.run_sync(SQLModel.metadata.create_all)
|
|
|
|
|
|
@api.on_event("shutdown")
|
|
async def close_connection_pool():
|
|
await db.engine.dispose()
|
|
|
|
|
|
@api.post("/states/", response_model=StateProvince)
|
|
async def create_state(state: StateProvince, session: AsyncSession = Depends(db.get_session)):
|
|
# db_obj = await crud.get_state_by_name_and_country(session, name=state.name, country=state.country)
|
|
# if db_obj:
|
|
# raise HTTPException(status_code=400, detail="Name already registered")
|
|
return await crud.create_state(session, state=state)
|
|
|
|
|
|
@api.get("/states/", response_model=list[StateProvince])
|
|
async def list_states(skip: int = 0, limit: int = 100, session: AsyncSession = Depends(db.get_session)):
|
|
return await crud.get_states(session, skip=skip, limit=limit)
|
|
|
|
|
|
# @app.post("/cities/", response_model=City)
|
|
# async def create_city(city: City, session: AsyncSession = Depends(get_session)):
|
|
# db_obj = await crud.get_state_by_name_and_country(session, name=state.name, country=state.country)
|
|
# if db_obj:
|
|
# raise HTTPException(status_code=400, detail="Name already registered")
|
|
# return await crud.create_state(session, state=state)
|