add migrations, fix imports

This commit is contained in:
ndmg 2026-11-07 19:35:15 +00:00
parent e2537b47ca
commit 1d3770ac1e
30 changed files with 378 additions and 64 deletions

149
alembic.ini Normal file
View File

@ -0,0 +1,149 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

1
alembic/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

86
alembic/env.py Normal file
View File

@ -0,0 +1,86 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
# Добавляем корень проекта в sys.path, чтобы импортировать твои модули
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Импортируем твой Base и настройки
from core.config import settings # Если у тебя настройки в Pydantic
from core.db import Base
# Импортируй ВСЕ модели, чтобы Alembic их увидел
from models import audio_model, photo_model, video_model
# (или как у тебя называется файл, где лежат все модели)
# this is the Alembic Config object
config = context.config
# Устанавливаем URL базы данных из твоих настроек
config.set_main_option("sqlalchemy.url", settings.database_url)
# ... дальше идет стандартный код ...
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
alembic/script.py.mako Normal file
View 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, Sequence[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"}

View File

@ -0,0 +1,42 @@
"""Initial migration
Revision ID: edca9d8e52b5
Revises:
Create Date: 2026-11-07 19:23:14.677545
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'edca9d8e52b5'
down_revision: Union[str, Sequence[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.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column('username', sa.VARCHAR(length=128), autoincrement=False, nullable=False),
sa.Column('hashed_password', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
sa.Column('isAdmin', sa.BOOLEAN(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('users_pkey'))
)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
# ### end Alembic commands ###

View File

@ -1,6 +1,5 @@
from authx import AuthX, AuthXConfig
from .config import settings
from core.config import settings
config = AuthXConfig(
JWT_SECRET_KEY=settings.SECRET_KEY,

View File

@ -2,6 +2,7 @@ import os
from pathlib import Path
from dotenv import load_dotenv
from pydantic_settings import BaseSettings, SettingsConfigDict
BASE_DIR = Path(__file__).resolve().parent.parent
@ -24,10 +25,22 @@ AUDIO_DIR = BASE_DIR / "media" / "audio"
COVERS = "_covers"
COVERS_DIR = AUDIO_DIR / COVERS
from pydantic_settings import BaseSettings
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_USER = os.getenv("DB_USER")
DB_NAME = os.getenv("DB_NAME")
DB_URL = f"postgresql+psycopg://{DB_USER}:{DB_PASSWORD}@127.0.0.1:5432/{DB_NAME}"
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore") # лучше ignore
# Добавь то, что есть в .env
DB_USER: str
DB_PASSWORD: str
DB_NAME: str
SECRET_KEY: str = os.getenv("SECRET_KEY")
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
@ -35,8 +48,9 @@ class Settings(BaseSettings):
COOKIE_SECURE: bool = False
COOKIE_SAMESITE: str = "lax"
COOKIE_DOMAIN: str | None = None
@property
def database_url(self) -> str:
return f"postgresql+psycopg://{self.DB_USER}:{self.DB_PASSWORD}@127.0.0.1:5432/{self.DB_NAME}"
class Config:
env_file = ".env"
settings = Settings()

View File

@ -1,6 +1,3 @@
import os
from dotenv import load_dotenv
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
@ -8,20 +5,12 @@ from sqlalchemy.ext.asyncio import (
)
from sqlalchemy.orm import DeclarativeBase
from .config import BASE_DIR
from .config import DB_URL
class Base(DeclarativeBase):
pass
dotenv_path = BASE_DIR / '.env'
load_dotenv(dotenv_path=dotenv_path)
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_USER = os.getenv("DB_USER")
DB_NAME = os.getenv("DB_NAME")
DB_URL = f"postgresql+psycopg://{DB_USER}:{DB_PASSWORD}@127.0.0.1:5432/{DB_NAME}"
engine = create_async_engine(DB_URL, echo=True)

24
main.py
View File

@ -5,7 +5,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from .core.config import (
from core.config import (
AUDIO_DIR,
COVERS_DIR,
PHOTOS_DIR_RESPNS,
@ -13,9 +13,9 @@ from .core.config import (
THUMBS_DIR,
YT_DIR,
)
from .core.db import Base, engine
from .routers import audio, auth, channel, photo, playlist, search, video
from .search.setup import setup_videos_index
from core.db import Base, engine
from routers import audio, auth, channel, photo, playlist, search, video
from search.setup import setup_videos_index
@asynccontextmanager
@ -41,11 +41,17 @@ app.add_middleware(
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/yt", StaticFiles(directory=YT_DIR), name="yt")
app.mount("/media", StaticFiles(directory=PHOTOS_DIR_RESPNS), name="media")
app.mount("/_thumbs", StaticFiles(directory=THUMBS_DIR), name="_thumbs")
app.mount("/_covers", StaticFiles(directory=COVERS_DIR), name="_covers")
app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio")
try:
app.mount("/yt", StaticFiles(directory=YT_DIR), name="yt")
app.mount("/media", StaticFiles(directory=PHOTOS_DIR_RESPNS), name="media")
app.mount("/_thumbs", StaticFiles(directory=THUMBS_DIR), name="_thumbs")
app.mount("/_covers", StaticFiles(directory=COVERS_DIR), name="_covers")
app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio")
except RuntimeError as err:
ValueError(err)
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():

0
models/__init__.py Normal file
View File

View File

@ -1,7 +1,7 @@
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from ..core.db import Base
from core.db import Base
class AudioPlaylist(Base):

View File

@ -3,7 +3,7 @@ from __future__ import annotations
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from ..core.db import Base
from core.db import Base
class Category(Base):

View File

@ -1,7 +1,7 @@
from sqlalchemy import Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from ..core.db import Base
from core.db import Base
class User(Base):

View File

@ -3,7 +3,7 @@ from datetime import date
from sqlalchemy import Date, ForeignKey, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from ..core.db import Base
from core.db import Base
class Channel(Base):

0
routers/__init__.py Normal file
View File

View File

@ -5,10 +5,10 @@ from fastapi.exceptions import HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.db import get_db
from ..models.audio_model import Audio, AudioPlaylist
from ..schemas.audio_schema import Audios, AudioSchema, Playlists
from core.authx import auth
from core.db import get_db
from models.audio_model import Audio, AudioPlaylist
from schemas.audio_schema import Audios, AudioSchema, Playlists
router = APIRouter()

View File

@ -2,11 +2,11 @@ from fastapi import APIRouter, Depends, HTTPException, Request, Response
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.db import get_db
from ..core.security import hash_password, verify_password
from ..models.users import User
from ..schemas.user_schema import UserCreate, UserLogin, UserRead
from core.authx import auth
from core.db import get_db
from core.security import hash_password, verify_password
from models.users import User
from schemas.user_schema import UserCreate, UserLogin, UserRead
router = APIRouter(prefix="/auth", tags=["auth"])

View File

@ -3,11 +3,11 @@ from fastapi.templating import Jinja2Templates
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.config import TEMPLATES_DIR
from ..core.db import get_db
from ..models.video_model import Channel, Playlist, Video
from ..schemas.channel_schemas import ChannelOut, ChannelsOut
from core.authx import auth
from core.config import TEMPLATES_DIR
from core.db import get_db
from models.video_model import Channel, Playlist, Video
from schemas.channel_schemas import ChannelOut, ChannelsOut
router = APIRouter()
templates = Jinja2Templates(directory=TEMPLATES_DIR)

View File

@ -2,10 +2,10 @@ from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.db import get_db
from ..models.photo_model import Category, Photo
from ..schemas.photo_schemas import CategoriesOut, PhotosOut, PhotosPaginatedOut
from core.authx import auth
from core.db import get_db
from models.photo_model import Category, Photo
from schemas.photo_schemas import CategoriesOut, PhotosOut, PhotosPaginatedOut
router = APIRouter()

View File

@ -3,11 +3,11 @@ from fastapi.templating import Jinja2Templates
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.config import TEMPLATES_DIR
from ..core.db import get_db
from ..models.video_model import Video
from ..schemas.playlist_schema import PlaylistOut
from core.authx import auth
from core.config import TEMPLATES_DIR
from core.db import get_db
from models.video_model import Video
from schemas.playlist_schema import PlaylistOut
router = APIRouter()
templates = Jinja2Templates(directory=TEMPLATES_DIR)

View File

@ -3,7 +3,7 @@ from fastapi import APIRouter, Query
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel
from ..search.search_client import videos_index
from search.search_client import videos_index
router = APIRouter(prefix="/search", tags=["search"])

View File

@ -5,10 +5,10 @@ from fastapi.exceptions import HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.authx import auth
from ..core.db import get_db
from ..models.video_model import Channel, Video
from ..schemas.video_schemas import VideoDetailOut, VideoOut, VideosResponse
from core.authx import auth
from core.db import get_db
from models.video_model import Channel, Video
from schemas.video_schemas import VideoDetailOut, VideoOut, VideosResponse
router = APIRouter()

0
schemas/__init__.py Normal file
View File

View File

@ -1,6 +1,6 @@
from pydantic import BaseModel, ConfigDict, field_validator
from ..services.path import encode_path
from services.path import encode_path
class AudioSchema(BaseModel):

View File

@ -2,7 +2,7 @@ from datetime import date as DateType
from pydantic import BaseModel, field_validator
from ..services.path import encode_path
from services.path import encode_path
class ChannelItem(BaseModel):

View File

@ -2,7 +2,7 @@ from __future__ import annotations
from pydantic import BaseModel, ConfigDict, field_validator
from ..services.path import encode_path
from services.path import encode_path
class PhotoItem(BaseModel):

View File

@ -2,7 +2,7 @@ from datetime import date as DateType
from pydantic import BaseModel, field_validator
from ..services.path import encode_path
from services.path import encode_path
class VideoItem(BaseModel):

View File

@ -2,7 +2,7 @@ from datetime import date as DateType
from pydantic import BaseModel, ConfigDict, field_validator
from ..services.path import encode_path
from services.path import encode_path
class VideoOut(BaseModel):

0
search/__init__.py Normal file
View File

View File

@ -3,7 +3,7 @@ import os
import meilisearch
from dotenv import load_dotenv
from ..core.config import BASE_DIR
from core.config import BASE_DIR
load_dotenv(BASE_DIR / '.env')