mirror of
https://github.com/stijndcl/didier.git
synced 2026-06-29 17:39:57 +02:00
Set up basics of SQLAlchemy
This commit is contained in:
parent
1ee9900891
commit
84bb04b711
7 changed files with 65 additions and 13 deletions
2
database/__init__.py
Normal file
2
database/__init__.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
from .db import engine, session, Base
|
||||
from .models import *
|
||||
16
database/db.py
Normal file
16
database/db.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from settings import DB_HOST, DB_NAME, DB_PASSWORD, DB_USERNAME, DB_DIALECT, DB_DRIVER
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
# Encode password
|
||||
_encoded_pw = quote_plus(DB_PASSWORD)
|
||||
|
||||
engine = create_engine(
|
||||
# Format: dialect+driver://username:password@host:port/database
|
||||
f"{DB_DIALECT}{'+' if DB_DRIVER else ''}{DB_DRIVER}://{DB_USERNAME}:{_encoded_pw}@{DB_HOST}/{DB_NAME}"
|
||||
)
|
||||
session = sessionmaker(bind=engine)()
|
||||
|
||||
Base = declarative_base()
|
||||
16
database/models.py
Normal file
16
database/models.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from database import Base
|
||||
from sqlalchemy import Column, String, Integer
|
||||
from typing import List
|
||||
|
||||
|
||||
class TestTable(Base):
|
||||
|
||||
__tablename__ = "test_table"
|
||||
|
||||
id = Column(Integer, autoincrement=True, primary_key=True)
|
||||
name = Column(String, nullable=False)
|
||||
|
||||
|
||||
# A list of all models in this file, this is used to
|
||||
# create all tables later on
|
||||
all_models: List[Base] = [TestTable]
|
||||
11
database/utils.py
Normal file
11
database/utils.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
from database import all_models, engine
|
||||
|
||||
|
||||
def create_all_tables():
|
||||
"""
|
||||
Create all tables in case they don't exist yet
|
||||
so the user doesn't have to do this manually
|
||||
when a new table is added
|
||||
"""
|
||||
for model in all_models:
|
||||
model.__table__.create(engine, checkfirst=True)
|
||||
Loading…
Add table
Add a link
Reference in a new issue