From 1c60f966972d7129aa4b07ea9f11cc3b0b58a3b3 Mon Sep 17 00:00:00 2001 From: "Waylon S. Walker" Date: Mon, 22 May 2023 08:24:01 -0500 Subject: [PATCH] create all on startup --- learn_sql_model/api/hero.py | 12 ++++++++++++ learn_sql_model/cli/hero.py | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/learn_sql_model/api/hero.py b/learn_sql_model/api/hero.py index f61f448..ec1ed24 100644 --- a/learn_sql_model/api/hero.py +++ b/learn_sql_model/api/hero.py @@ -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 diff --git a/learn_sql_model/cli/hero.py b/learn_sql_model/cli/hero.py index 11c2e99..f9c0243 100644 --- a/learn_sql_model/cli/hero.py +++ b/learn_sql_model/cli/hero.py @@ -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)