generateur_v3/backend/api/database/db.py

26 lines
674 B
Python
Raw Normal View History

2022-10-10 01:34:38 +02:00
import json
2023-02-28 10:21:08 +01:00
import pydantic.json
from sqlmodel import SQLModel, create_engine, Session
2022-09-16 21:50:55 +02:00
2023-02-22 12:43:39 +01:00
sqlite_file_name = "database7.db"
2022-09-16 21:50:55 +02:00
sqlite_url = f"sqlite:///{sqlite_file_name}"
2022-10-10 01:34:38 +02:00
def _custom_json_serializer(*args, **kwargs) -> str:
"""
Encodes json in the same way that pydantic does.
"""
2023-02-28 10:21:08 +01:00
2022-10-10 01:34:38 +02:00
return json.dumps(*args, default=pydantic.json.pydantic_encoder, **kwargs)
engine = create_engine(sqlite_url, echo=False, connect_args={"check_same_thread": False}, json_serializer=_custom_json_serializer)
2022-09-16 21:50:55 +02:00
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def get_session():
2023-02-22 12:43:39 +01:00
with Session(engine, expire_on_commit=False) as s:
2022-09-16 21:50:55 +02:00
yield s