feat: added seseion for sqlite, alembic and ruff, model Timerr, schemas.py, mixin for id, cruds: create timer, get timer, settings.py for db
This commit is contained in:
0
kawai_focus/database/__init__.py
Normal file
0
kawai_focus/database/__init__.py
Normal file
1
kawai_focus/database/alembic/README
Normal file
1
kawai_focus/database/alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
85
kawai_focus/database/alembic/env.py
Normal file
85
kawai_focus/database/alembic/env.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
from kawai_focus.settings import settings
|
||||
from kawai_focus.database.models import Base
|
||||
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
config.set_main_option("sqlalchemy.url", settings.db_settings.get_url_db)
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
28
kawai_focus/database/alembic/script.py.mako
Normal file
28
kawai_focus/database/alembic/script.py.mako
Normal file
@@ -0,0 +1,28 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""migrration timer
|
||||
|
||||
Revision ID: e3e6ab4aede7
|
||||
Revises:
|
||||
Create Date: 2025-05-06 20:26:18.791745
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "e3e6ab4aede7"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"timer",
|
||||
sa.Column("название", sa.String(length=200), nullable=False),
|
||||
sa.Column("время помидора", sa.Integer(), nullable=False),
|
||||
sa.Column("время перерыва", sa.Integer(), nullable=False),
|
||||
sa.Column("время долгого перерыва", sa.Integer(), nullable=False),
|
||||
sa.Column("количество помидоров", sa.Integer(), nullable=False),
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("timer")
|
||||
# ### end Alembic commands ###
|
||||
57
kawai_focus/database/cruds.py
Normal file
57
kawai_focus/database/cruds.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from sqlalchemy import select, insert
|
||||
from sqlalchemy.exc import SQLAlchemyError, OperationalError, NoResultFound
|
||||
from pydantic import ValidationError
|
||||
|
||||
from kawai_focus.schemas import TimerModel
|
||||
from kawai_focus.database.session import db
|
||||
from kawai_focus.database.models import Timer
|
||||
from kawai_focus.main import Logger
|
||||
|
||||
|
||||
def get_timer(timer_id: int) -> TimerModel:
|
||||
"""Функция для получения данных таймера"""
|
||||
|
||||
try:
|
||||
with db.get_session() as session:
|
||||
timer_model = Timer
|
||||
query = select(
|
||||
timer_model.id,
|
||||
timer_model.title,
|
||||
timer_model.pomodoro_time,
|
||||
timer_model.break_time,
|
||||
timer_model.break_long_time,
|
||||
timer_model.count_pomodoro
|
||||
).where(timer_id == timer_model.id)
|
||||
result = session.execute(query)
|
||||
timer = result.mappings().first()
|
||||
|
||||
return TimerModel.model_validate(obj=timer, from_attributes=True)
|
||||
except (ConnectionError, SQLAlchemyError, TimeoutError, OperationalError, ValidationError, NoResultFound) as err:
|
||||
Logger.error(f'{err.__class__.__name__}: {err}')
|
||||
|
||||
|
||||
def new_timer(data: TimerModel) -> bool | None:
|
||||
"""Функция для создания нового таймера"""
|
||||
|
||||
try:
|
||||
with db.get_session() as session:
|
||||
timer_model = Timer
|
||||
query = insert(timer_model).values(**data.model_dump())
|
||||
session.execute(query)
|
||||
session.commit()
|
||||
except (ConnectionError, SQLAlchemyError, TimeoutError, OperationalError, ValidationError) as err:
|
||||
Logger.error(f'{err.__class__.__name__}: {err}')
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# new_timer(data=TimerValidModel(
|
||||
# title='test_timer_2',
|
||||
# pomodoro_time=50,
|
||||
# break_long_time=25,
|
||||
# break_time=5,
|
||||
# count_pomodoro=4
|
||||
# ))
|
||||
|
||||
print(get_timer(timer_id=1))
|
||||
13
kawai_focus/database/mixins.py
Normal file
13
kawai_focus/database/mixins.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import Integer
|
||||
|
||||
|
||||
class IDMixin:
|
||||
"""Базовый класс для моделей с id"""
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='id',
|
||||
primary_key=True,
|
||||
autoincrement=True
|
||||
)
|
||||
46
kawai_focus/database/models.py
Normal file
46
kawai_focus/database/models.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped
|
||||
from sqlalchemy import Integer, String
|
||||
|
||||
from kawai_focus.database.mixins import IDMixin
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Класс для корректной работы аннотаций"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class Timer(IDMixin, Base):
|
||||
"""Модель таймера"""
|
||||
|
||||
__tablename__ = 'timer'
|
||||
|
||||
title: Mapped[str] = mapped_column(
|
||||
String(length=200),
|
||||
name='название',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
pomodoro_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время помидора',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
break_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время перерыва',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
break_long_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время долгого перерыва',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
count_pomodoro: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='количество помидоров',
|
||||
nullable=False
|
||||
)
|
||||
28
kawai_focus/database/session.py
Normal file
28
kawai_focus/database/session.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
|
||||
from kawai_focus.settings import settings
|
||||
|
||||
|
||||
class SessionDB:
|
||||
"""Класс для управления подключением к базе данных."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._engine = create_engine(
|
||||
url=settings.db_settings.get_url_db,
|
||||
echo=settings.db_settings.echo_db
|
||||
)
|
||||
self._session_factory = sessionmaker(
|
||||
bind=self._engine,
|
||||
expire_on_commit=False,
|
||||
autocommit=False
|
||||
)
|
||||
|
||||
@property
|
||||
def get_session(self) -> Session:
|
||||
"""Метод для получения сессии"""
|
||||
|
||||
return self._session_factory
|
||||
|
||||
|
||||
db = SessionDB()
|
||||
32
kawai_focus/schemas.py
Normal file
32
kawai_focus/schemas.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from pydantic import BaseModel, field_validator, Field
|
||||
from kawai_focus.utils.errors import ErrorMessage
|
||||
|
||||
|
||||
class TimerModel(BaseModel):
|
||||
"""Модель для валидации данных таймера"""
|
||||
|
||||
id: int | None = None
|
||||
title: str
|
||||
pomodoro_time: int
|
||||
break_time: int
|
||||
break_long_time: int
|
||||
count_pomodoro: int
|
||||
|
||||
|
||||
class TimerTimeModel(BaseModel):
|
||||
"""Модель для валидации времени таймера"""
|
||||
|
||||
hh: int = Field(0, ge=0, le=23)
|
||||
mm: int = Field(0, ge=0, le=59)
|
||||
ss: int = Field(0, ge=0, le=59)
|
||||
|
||||
@field_validator('hh', 'mm', 'ss')
|
||||
@classmethod
|
||||
def check_all_time_fields(cls, value: int) -> int:
|
||||
"""Метод валидирует все поля времени"""
|
||||
|
||||
# гарантирует, что время не равно 00:00:00
|
||||
if value == 0:
|
||||
raise ValueError(ErrorMessage.NO_TIME.value)
|
||||
|
||||
return value
|
||||
@@ -3,7 +3,7 @@ from kivy.clock import Clock
|
||||
from kivy.core.audio import SoundLoader
|
||||
|
||||
from kawai_focus.utils.utils import custom_timer, data_json
|
||||
from kawai_focus.utils.validators import TimerValidator
|
||||
from kawai_focus.schemas import TimerTimeModel
|
||||
|
||||
|
||||
class TimerScreen(Screen):
|
||||
@@ -29,7 +29,7 @@ class TimerScreen(Screen):
|
||||
self.paused = False
|
||||
else:
|
||||
# Инициализация генератора таймера
|
||||
vaid_timer_data = TimerValidator(ss=12) # Установите необходимое время
|
||||
vaid_timer_data = TimerTimeModel(ss=12) # Установите необходимое время
|
||||
self.timer_generator = custom_timer(valid_data=vaid_timer_data)
|
||||
self.remaining_time = next(self.timer_generator, self.zero_time)
|
||||
|
||||
|
||||
33
kawai_focus/settings.py
Normal file
33
kawai_focus/settings.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class ModelConfig(BaseSettings):
|
||||
"""Модель конфигурации"""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file='.env',
|
||||
env_file_encoding='utf-8',
|
||||
extra='ignore'
|
||||
)
|
||||
|
||||
|
||||
class SettingsDB(ModelConfig):
|
||||
"""Класс для данных БД"""
|
||||
|
||||
name_db: str
|
||||
echo_db: bool
|
||||
|
||||
@property
|
||||
def get_url_db(self) -> str:
|
||||
"""Метод вернёт URL для подключения к БД"""
|
||||
|
||||
return f'sqlite:///{self.name_db}'
|
||||
|
||||
|
||||
class Settings(ModelConfig):
|
||||
"""Класс для данных конфига"""
|
||||
|
||||
db_settings: SettingsDB = SettingsDB()
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -4,7 +4,7 @@ from os import path, listdir
|
||||
|
||||
from kawai_focus.main import Logger
|
||||
from kawai_focus.utils.errors import ErrorMessage
|
||||
from kawai_focus.utils.validators import TimerValidator
|
||||
from kawai_focus.schemas import TimerTimeModel
|
||||
|
||||
|
||||
class ReadJson:
|
||||
@@ -44,7 +44,7 @@ class ReadJson:
|
||||
data_json = ReadJson(folder_json='json')
|
||||
|
||||
|
||||
def custom_timer(valid_data: TimerValidator) -> Generator[str, None, None]:
|
||||
def custom_timer(valid_data: TimerTimeModel) -> Generator[str, None, None]:
|
||||
"""Функция отсчитывает время, установленное для таймера в формате
|
||||
'hh:mm:ss'. Возвращает генератор, который возвращает текущее время
|
||||
в формате 'hh:mm:ss'."""
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
from kawai_focus.utils.errors import ErrorMessage
|
||||
|
||||
|
||||
@dataclass
|
||||
class TimerValidator:
|
||||
"""Класс для валидации функции таймера."""
|
||||
|
||||
hh: int = 0
|
||||
mm: int = 0
|
||||
ss: int = 0
|
||||
|
||||
def __post_init__(self):
|
||||
if not all(isinstance(value, int) for value in (self.hh, self.mm, self.ss)):
|
||||
raise TypeError(ErrorMessage.NOT_INT_TYPE.value)
|
||||
|
||||
if self.ss == 0 and self.mm == 0 and self.hh == 0:
|
||||
raise ValueError(ErrorMessage.NO_TIME.value)
|
||||
|
||||
if self.ss < 0 or self.mm < 0 or self.hh < 0:
|
||||
raise ValueError(ErrorMessage.NEGATIVE_TIME.value)
|
||||
|
||||
if self.ss > 59 or self.mm > 59:
|
||||
raise ValueError(ErrorMessage.SS_MM_BIG.value)
|
||||
|
||||
if self.hh > 23:
|
||||
raise ValueError(ErrorMessage.HH_BIG.value)
|
||||
|
||||
Reference in New Issue
Block a user