create all on startup

This commit is contained in:
Waylon Walker 2023-05-22 08:24:01 -05:00
parent ad6471da8c
commit 1c60f96697
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
2 changed files with 46 additions and 3 deletions

View file

@ -1,13 +1,20 @@
from typing import Annotated
from fastapi import APIRouter, Depends
from sqlmodel import SQLModel
from learn_sql_model.api.user import oauth2_scheme
from learn_sql_model.config import get_config
from learn_sql_model.models.hero import Hero
hero_router = APIRouter()
@hero_router.on_event("startup")
def on_startup() -> None:
SQLModel.metadata.create_all(get_config().database.engine)
@hero_router.get("/items/")
async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
return {"token": token}
@ -29,3 +36,8 @@ def post_hero(hero: Hero) -> Hero:
def get_heros() -> list[Hero]:
"get all heros"
return Hero().get()
# Alternatively
# with get_config().database.session as session:
# statement = select(Hero)
# results = session.exec(statement).all()
# return results

View file

@ -2,9 +2,14 @@ from typing import List, Union
from pydantic_typer import expand_pydantic_args
from rich.console import Console
from sqlmodel import SQLModel
import typer
from learn_sql_model.config import Config, get_config
from learn_sql_model.factories.hero import HeroFactory
from learn_sql_model.factories.pet import PetFactory
from learn_sql_model.models.hero import Hero
from learn_sql_model.models.pet import Pet
hero_app = typer.Typer()
@ -12,19 +17,45 @@ hero_app = typer.Typer()
@hero_app.callback()
def hero():
"model cli"
SQLModel.metadata.create_all(get_config().database.engine)
@hero_app.command()
def get(id: int = None) -> Union[Hero, List[Hero]]:
"get one hero"
hero = Hero().get(item_id=id)
hero = Hero().get(id=id)
Console().print(hero)
return hero
@hero_app.command()
@expand_pydantic_args(typer=True)
def create(hero: Hero) -> Hero:
def create(
hero: Hero,
pet: Pet = None,
config: Config = None,
) -> Hero:
"read all the heros"
hero = hero.post()
hero.pet = pet
hero = hero.post(config=config)
Console().print(hero)
@hero_app.command()
@expand_pydantic_args(typer=True)
def populate(
n: int = 10,
config: Config = None,
) -> Hero:
"read all the heros"
if config is None:
config = Config()
if config.env == "prod":
Console().print("populate is not supported in production")
return
for hero in HeroFactory().batch(n):
pet = PetFactory().build()
hero.pet = pet
Console().print(hero)
hero.post(config=config)