feature: Füge dotEnv configuration hinzu
This commit is contained in:
+25
-8
@@ -1,28 +1,35 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import FastAPI
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from api.models import Car, FuelItem
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
sqlite_file_name = "database.db"
|
||||
sqlite_url = f"sqlite:///{sqlite_file_name}"
|
||||
|
||||
class Settings(BaseSettings):
|
||||
database_url: str = ""
|
||||
sqlite_file_name: str = ""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env")
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
database_url = settings.database_url
|
||||
|
||||
connect_args = {
|
||||
"check_same_thread": False
|
||||
}
|
||||
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
|
||||
engine = create_engine(database_url, echo=True, connect_args=connect_args)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# startup
|
||||
create_db_and_tables()
|
||||
def fill_database():
|
||||
car = Car(id_string="Auto 1")
|
||||
with Session(engine) as session:
|
||||
session.add(car)
|
||||
@@ -37,6 +44,16 @@ async def lifespan(app: FastAPI):
|
||||
session.add(fill_item)
|
||||
session.commit()
|
||||
session.refresh(fill_item)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# startup
|
||||
create_db_and_tables()
|
||||
try:
|
||||
fill_database()
|
||||
except IntegrityError as e:
|
||||
print(e)
|
||||
yield
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user