инициализация проекта

This commit is contained in:
Андрей Дувакин 2025-11-26 19:58:54 +05:00
parent 62c79cf469
commit 3947cdfc79
31 changed files with 553 additions and 0 deletions

3
.gitignore vendored
View File

@ -1,3 +1,6 @@
api/.idea
.idea
# ---> Node
# Logs
logs

147
api/alembic.ini Normal file
View File

@ -0,0 +1,147 @@
# 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/app/database/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
# 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

0
api/app/__init__.py Normal file
View File

View File

View File

View File

View File

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

View File

@ -0,0 +1,37 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import create_async_engine
from app.domain.models import Base
from app.settings import get_db_url
config = context.config
if config.config_file_name:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
async def run_migrations_online():
print(get_db_url())
connectable = create_async_engine(get_db_url(), poolclass=pool.NullPool, future=True)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
def do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def main():
await run_migrations_online()
import asyncio
asyncio.run(main())

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,32 @@
"""0001 инициализация
Revision ID: 7a6554b361e8
Revises:
Create Date: 2025-11-26 19:52:23.751193
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '7a6554b361e8'
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! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

View File

@ -0,0 +1,15 @@
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from app.settings import get_db_url
engine = create_async_engine(get_db_url(), echo=False)
async_session_maker = sessionmaker(
bind=engine, class_=AsyncSession, expire_on_commit=False
)
async def get_db():
async with async_session_maker() as session:
yield session

View File

View File

View File

@ -0,0 +1,10 @@
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
from app.settings import Settings
metadata_obj = MetaData(schema=Settings().db_schema)
class Base(DeclarativeBase):
metadata = metadata_obj

View File

@ -0,0 +1,28 @@
from datetime import datetime
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from app.domain.models import Base
class RootTable(Base):
__abstract__ = True
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=False)
created_at: Mapped[datetime] = mapped_column(default=func.now())
updated_at: Mapped[datetime] = mapped_column(default=func.now(), onupdate=func.now())
class PhotoAbstract(RootTable):
__abstract__ = True
photo_filename: Mapped[str] = mapped_column()
photo_path: Mapped[str] = mapped_column()
class FileAbstract(RootTable):
__abstract__ = True
filename: Mapped[str] = mapped_column()
file_path: Mapped[str] = mapped_column()

View File

@ -0,0 +1,14 @@
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class CourseTeacher(RootTable):
__tablename__ = 'course_teachers'
course_id: Mapped[int] = mapped_column(ForeignKey('courses.id'), nullable=False)
teacher_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
course: Mapped['Course'] = relationship('Course', back_populates='teachers')
teacher: Mapped['User'] = relationship('User', back_populates='teacher_courses')

View File

@ -0,0 +1,18 @@
from typing import List
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import PhotoAbstract
class Course(PhotoAbstract):
__tablename__ = 'courses'
title: Mapped[str] = mapped_column(String(250), nullable=False)
description: Mapped[str] = mapped_column(String(1000))
teachers: Mapped[List['CourseTeacher']] = relationship('CourseTeacher', back_populates='course')
enrollments: Mapped[List['Enrollment']] = relationship('Enrollment', back_populates='course')
lessons: Mapped[List['Lesson']] = relationship('Lesson', back_populates='course')
tasks: Mapped[List['Task']] = relationship('Task', back_populates='course')

View File

@ -0,0 +1,18 @@
from datetime import datetime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Enrollment(RootTable):
__tablename__ = 'enrollments'
enrollment_date: Mapped[datetime] = mapped_column(nullable=False)
course_id: Mapped[int] = mapped_column(ForeignKey('courses.id'), nullable=False)
student_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
course: Mapped['Course'] = relationship('Course', back_populates='enrollments')
student: Mapped['User'] = relationship('User', back_populates='enrollments')

View File

@ -0,0 +1,12 @@
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import FileAbstract
class LessonFile(FileAbstract):
__tablename__ = 'lesson_files'
lesson_id: Mapped[int] = mapped_column(ForeignKey('lessons.id'), nullable=False)
lesson: Mapped['Lesson'] = relationship('Lesson', back_populates='files')

View File

@ -0,0 +1,23 @@
from typing import List
from sqlalchemy import String, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Lesson(RootTable):
__tablename__ = 'lessons'
title: Mapped[str] = mapped_column(String(250), nullable=False)
description: Mapped[str] = mapped_column()
text: Mapped[str] = mapped_column()
number: Mapped[int] = mapped_column(nullable=False)
course_id: Mapped[int] = mapped_column(ForeignKey('courses.id'), nullable=False)
creator_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
course: Mapped['Course'] = relationship('Course', back_populates='lessons')
creator: Mapped['User'] = relationship('User', back_populates='created_lessons')
files: Mapped[List['LessonFile']] = relationship('LessonFile', back_populates='lessons')

View File

@ -0,0 +1,14 @@
from typing import List
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Role(RootTable):
__tablename__ = 'roles'
title: Mapped[str] = mapped_column(String(150), unique=True, nullable=False)
users: Mapped[List['User']] = relationship('User', back_populates='role')

View File

@ -0,0 +1,12 @@
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import FileAbstract
class SolutionFile(FileAbstract):
__tablename__ = 'solution_files'
solution_id: Mapped[int] = mapped_column(ForeignKey('solutions.id'), nullable=False)
solution: Mapped['Solution'] = relationship('Solution', back_populates='files')

View File

@ -0,0 +1,23 @@
from typing import List
from sqlalchemy import String, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Solution(RootTable):
__tablename__ = 'solutions'
answer_text: Mapped[str] = mapped_column()
assessment_text: Mapped[str] = mapped_column(String(50))
assessment_autor_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
task_id: Mapped[int] = mapped_column(ForeignKey('tasks.id'), nullable=False)
student_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
assessment_autor: Mapped['User'] = relationship('User', back_populates='assessments',
foreign_keys=[assessment_autor_id])
student: Mapped['User'] = relationship('User', back_populates='my_solutions', foreign_keys=[student_id])
files: Mapped[List['SolutionFile']] = relationship('SolutionFile', back_populates='solution')

View File

@ -0,0 +1,14 @@
from typing import List
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Status(RootTable):
__tablename__ = 'statuses'
title: Mapped[str] = mapped_column(String(250), nullable=False, unique=True)
users = Mapped[List['User']] = relationship('User', back_populates='status')

View File

@ -0,0 +1,12 @@
from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import FileAbstract
class TaskFile(FileAbstract):
__tablename__ = 'task_files'
task_id: Mapped[int] = mapped_column(ForeignKey('tasks.id'), nullable=False)
task: Mapped['Task'] = relationship('Task', back_populates='files')

View File

@ -0,0 +1,23 @@
from typing import List
from sqlalchemy import String, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.domain.models.base import RootTable
class Task(RootTable):
__tablename__ = 'tasks'
title: Mapped[str] = mapped_column(String(250), nullable=False)
description: Mapped[str] = mapped_column()
text: Mapped[str] = mapped_column()
number: Mapped[int] = mapped_column(nullable=False)
course_id: Mapped[int] = mapped_column(ForeignKey('courses.id'), nullable=False)
creator_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
course: Mapped['Course'] = relationship('Course', back_populates='tasks')
creator: Mapped['User'] = relationship('User', back_populates='created_tasks')
files: Mapped[List['TaskFile']] = relationship('TaskFile', back_populates='lessons')

View File

@ -0,0 +1,45 @@
from datetime import date, datetime
from typing import List
from sqlalchemy import String, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from app.domain.models.base import PhotoAbstract
class User(PhotoAbstract):
__tablename__ = 'users'
first_name: Mapped[str] = mapped_column(String(250), nullable=False)
last_name: Mapped[str] = mapped_column(String(250), nullable=False)
patronymic: Mapped[str] = mapped_column(String(250))
login: Mapped[str] = mapped_column(String(250), nullable=False, unique=True)
password_hash: Mapped[str] = mapped_column(nullable=False)
email: Mapped[str] = mapped_column(String(250), unique=True)
birthdate: Mapped[date] = mapped_column(nullable=False)
reg_date: Mapped[date] = mapped_column(nullable=False, default=func.now())
last_visit: Mapped[datetime] = mapped_column()
photo_filename: Mapped[str] = mapped_column(String(250))
photo_path: Mapped[str] = mapped_column()
status_id: Mapped[int] = mapped_column(ForeignKey('statuses.id'), nullable=False)
role_id: Mapped[int] = mapped_column(ForeignKey('roles.id'), nullable=False)
status: Mapped['Status'] = relationship('Status', back_populates='users', lazy='joined')
role: Mapped['Role'] = relationship('Role', back_populates='users', lazy='joined')
teacher_courses: Mapped[List['CourseTeacher']] = relationship('CourseTeacher', back_populates='teacher')
enrollments: Mapped[List['Enrollment']] = relationship('Enrollment', back_populates='student')
created_lessons: Mapped[List['Lesson']] = relationship('Lesson', back_populates='creator')
created_tasks: Mapped[List['Task']] = relationship('Task', back_populates='creator')
assessments: Mapped[List['Solution']] = relationship(
'Solution',
back_populates='assessment_autor',
foreign_keys=['assessment_autor_id'],
)
my_solutions: Mapped[List['Solution']] = relationship(
'Solution',
back_populates='student',
foreign_keys=['student_id'],
)

View File

0
api/app/main.py Normal file
View File

19
api/app/settings.py Normal file
View File

@ -0,0 +1,19 @@
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8')
db_driver: str = Field(alias='DB_DRIVER')
db_host: str = Field(alias='DB_HOST')
db_port: int = Field(alias='DB_PORT')
db_user: str = Field(alias='DB_USER')
db_password: str = Field(alias='DB_PASSWORD')
db_name: str = Field(alias='DB_NAME')
db_schema: str = Field(alias='DB_SCHEMA')
def get_db_url() -> str:
settings = Settings()
return f'{settings.db_driver}://{settings.db_user}:{settings.db_password}@{settings.db_host}:{settings.db_port}/{settings.db_name}'

5
api/req.txt Normal file
View File

@ -0,0 +1,5 @@
sqlalchemy==2.0.44
pydantic-settings==2.12.0
alembic==1.17.2
asyncpg==0.31.0
greenlet==3.2.4