versione prima dle menu della clincia
This commit is contained in:
1
backend/app/db/__init__.py
Normal file
1
backend/app/db/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Database package.
|
||||
5
backend/app/db/base.py
Normal file
5
backend/app/db/base.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
24
backend/app/db/init_db.py
Normal file
24
backend/app/db/init_db.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import hashlib
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.base import Base
|
||||
from app.db.session import SessionLocal, engine
|
||||
from app.models import TestUser
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
Base.metadata.create_all(bind=engine)
|
||||
seed_test_data()
|
||||
|
||||
|
||||
def seed_test_data() -> None:
|
||||
with SessionLocal() as db:
|
||||
existing_user = db.scalar(select(TestUser).where(TestUser.username == "admin_test"))
|
||||
if existing_user:
|
||||
return
|
||||
|
||||
password_hash = hashlib.sha256("change_me_123".encode("utf-8")).hexdigest()
|
||||
db.add(TestUser(username="admin_test", password_hash=password_hash))
|
||||
db.commit()
|
||||
25
backend/app/db/session.py
Normal file
25
backend/app/db/session.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.config import settings
|
||||
|
||||
if settings.sqlite_file_path:
|
||||
Path(settings.sqlite_file_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
settings.database_url,
|
||||
connect_args={"check_same_thread": False} if settings.database_url.startswith("sqlite") else {},
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user