many changes
This commit is contained in:
204
backend/.gitignore
vendored
Normal file
204
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,204 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
#poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
|
||||
data
|
||||
3
backend/.idea/.gitignore
generated
vendored
Normal file
3
backend/.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
10
backend/.idea/backend.iml
generated
Normal file
10
backend/.idea/backend.iml
generated
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.13 (backend) (2)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
backend/.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
6
backend/.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
7
backend/.idea/misc.xml
generated
Normal file
7
backend/.idea/misc.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.13 (backend) (2)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13 (backend) (2)" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
8
backend/.idea/modules.xml
generated
Normal file
8
backend/.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/backend.iml" filepath="$PROJECT_DIR$/.idea/backend.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
backend/.idea/vcs.xml
generated
Normal file
6
backend/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
0
backend/Dockerfile
Normal file
0
backend/Dockerfile
Normal file
141
backend/alembic.ini
Normal file
141
backend/alembic.ini
Normal file
@@ -0,0 +1,141 @@
|
||||
# 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/migrations
|
||||
|
||||
# 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 python>=3.9 or backports.zoneinfo library and tzdata library.
|
||||
# Any required deps can 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 exec runner, execute a binary
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = %(here)s/.venv/bin/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
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
3
backend/app/config.py
Normal file
3
backend/app/config.py
Normal file
@@ -0,0 +1,3 @@
|
||||
database_url = "sqlite+aiosqlite:///data/database.sqlite"
|
||||
|
||||
PAGINATION_DEFAULT_LIMIT = 10
|
||||
7
backend/app/controllers/__init__.py
Normal file
7
backend/app/controllers/__init__.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from .auth_controller import auth_router
|
||||
from .user_controller import user_router
|
||||
|
||||
routers = [
|
||||
user_router,
|
||||
auth_router
|
||||
]
|
||||
13
backend/app/controllers/auth_controller.py
Normal file
13
backend/app/controllers/auth_controller.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
auth_router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
@auth_router.post("/login")
|
||||
async def authenticate_user():
|
||||
pass
|
||||
|
||||
|
||||
@auth_router.post("/logout")
|
||||
async def logout_user():
|
||||
pass
|
||||
79
backend/app/controllers/user_controller.py
Normal file
79
backend/app/controllers/user_controller.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from pprint import pprint
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import config
|
||||
from app.depends import get_session_without_commit, get_session_with_commit
|
||||
from app.exceptions import ObjectNotFoundException
|
||||
from app.models import User
|
||||
from app.repositories import UserRepository
|
||||
from app.schemas import UserSchema, UserCreateSchema, PaginationSchema
|
||||
from app.schemas.user_schemas import UserUpdateSchema
|
||||
|
||||
user_router = APIRouter(prefix="/user", tags=["User"])
|
||||
|
||||
|
||||
@user_router.get("/{user_id}")
|
||||
async def get_user(user_id: int, session: AsyncSession = Depends(get_session_without_commit)) -> UserSchema:
|
||||
user_repository = UserRepository(session)
|
||||
try:
|
||||
user = await user_repository.get(user_id)
|
||||
return UserSchema.model_validate(user)
|
||||
except ObjectNotFoundException:
|
||||
return status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
@user_router.post("")
|
||||
async def create_user(schema: UserCreateSchema, session: AsyncSession = Depends(get_session_with_commit)) -> UserSchema:
|
||||
user_repository = UserRepository(session)
|
||||
model = User(**schema.model_dump(exclude_unset=True))
|
||||
await user_repository.add(model)
|
||||
return status.HTTP_201_CREATED
|
||||
|
||||
|
||||
@user_router.put("/{user_id}")
|
||||
async def edit_user(user_id: int, schema: UserUpdateSchema,
|
||||
session: AsyncSession = Depends(get_session_with_commit)) -> UserSchema:
|
||||
user_repository = UserRepository(session)
|
||||
try:
|
||||
rows_count = await user_repository.update(user_id, schema)
|
||||
if rows_count > 0:
|
||||
return status.HTTP_202_ACCEPTED
|
||||
else:
|
||||
raise ObjectNotFoundException
|
||||
except ObjectNotFoundException:
|
||||
return status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
@user_router.delete("/{user_id}")
|
||||
async def delete_user(user_id: int, session: AsyncSession = Depends(get_session_with_commit)):
|
||||
user_repository = UserRepository(session)
|
||||
rows_count = await user_repository.delete(user_id)
|
||||
if rows_count == 1:
|
||||
return status.HTTP_202_ACCEPTED
|
||||
return status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
@user_router.get("")
|
||||
async def get_all_users(
|
||||
page: int = 1,
|
||||
limit: int = config.PAGINATION_DEFAULT_LIMIT,
|
||||
session: AsyncSession = Depends(get_session_without_commit)) -> PaginationSchema[UserSchema]:
|
||||
user_repository = UserRepository(session)
|
||||
users = await user_repository.get_all()
|
||||
|
||||
users_count = len(users)
|
||||
pages_count = users_count // limit + min(users_count % limit, 1)
|
||||
|
||||
page_obj = PaginationSchema(
|
||||
items=[UserSchema.model_validate(obj) for obj in users[(page - 1) * limit: (page - 1 + 1) * limit]],
|
||||
page=page,
|
||||
total_items=users_count,
|
||||
last_page=pages_count,
|
||||
total_pages=pages_count,
|
||||
items_by_page=limit,
|
||||
has_next_page=page < pages_count,
|
||||
has_prev_page=page > 1
|
||||
)
|
||||
return page_obj
|
||||
1
backend/app/depends/__init__.py
Normal file
1
backend/app/depends/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .session import get_session_with_commit, get_session_without_commit
|
||||
28
backend/app/depends/session.py
Normal file
28
backend/app/depends/session.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.utils import async_session_maker
|
||||
|
||||
|
||||
async def get_session_with_commit() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_maker() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def get_session_without_commit() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with async_session_maker() as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
1
backend/app/exceptions/__init__.py
Normal file
1
backend/app/exceptions/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .general import ObjectNotFoundException
|
||||
2
backend/app/exceptions/general.py
Normal file
2
backend/app/exceptions/general.py
Normal file
@@ -0,0 +1,2 @@
|
||||
class ObjectNotFoundException(Exception):
|
||||
pass
|
||||
12
backend/app/main.py
Normal file
12
backend/app/main.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from fastapi import FastAPI, APIRouter
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
main_router = APIRouter(prefix="/api")
|
||||
|
||||
from app.controllers import routers
|
||||
|
||||
for router in routers:
|
||||
main_router.include_router(router)
|
||||
|
||||
app.include_router(main_router)
|
||||
2
backend/app/models/__init__.py
Normal file
2
backend/app/models/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from .abstract_model import AbstractModel
|
||||
from .user_model import User
|
||||
13
backend/app/models/abstract_model.py
Normal file
13
backend/app/models/abstract_model.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class AbstractModel(DeclarativeBase):
|
||||
__abstract__ = True
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, index=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"<{self.__class__.__name__}(id={self.id})>"
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
14
backend/app/models/user_model.py
Normal file
14
backend/app/models/user_model.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import mapped_column, Mapped
|
||||
|
||||
from .abstract_model import AbstractModel
|
||||
|
||||
|
||||
class User(AbstractModel):
|
||||
__tablename__ = "users"
|
||||
|
||||
name: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
surname: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
patronymic: Mapped[str] = mapped_column(String(50), nullable=True)
|
||||
email: Mapped[str] = mapped_column(String(256), nullable=False, unique=True, index=True)
|
||||
password: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||
2
backend/app/repositories/__init__.py
Normal file
2
backend/app/repositories/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from .base_repository import BaseRepository
|
||||
from .user_repository import UserRepository
|
||||
40
backend/app/repositories/base_repository.py
Normal file
40
backend/app/repositories/base_repository.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import itertools
|
||||
from typing import Type
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import AbstractModel
|
||||
|
||||
|
||||
class BaseRepository[TModel: AbstractModel]:
|
||||
def __init__(self, session: AsyncSession, model: Type[TModel]):
|
||||
self.__session = session
|
||||
self.__model = model
|
||||
|
||||
async def get(self, model_id: int) -> TModel | None:
|
||||
query = select(self.__model).filter_by(id=model_id)
|
||||
result = await self.__session.execute(query)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def add(self, model: TModel) -> TModel:
|
||||
self.__session.add(model)
|
||||
await self.__session.flush()
|
||||
return model
|
||||
|
||||
async def update(self, model_id: int, model: TModel) -> int:
|
||||
query = update(self.__model).where(self.__model.id == model_id).values(**model.model_dump(exclude_unset=True))
|
||||
result = await self.__session.execute(query)
|
||||
await self.__session.flush()
|
||||
return result.rowcount()
|
||||
|
||||
async def delete(self, model_id: int):
|
||||
obj = await self.get(model_id)
|
||||
await self.__session.delete(obj)
|
||||
await self.__session.flush()
|
||||
return obj
|
||||
|
||||
async def get_all(self):
|
||||
query = select(self.__model)
|
||||
result = await self.__session.execute(query)
|
||||
return tuple(itertools.chain.from_iterable(result.all()))
|
||||
10
backend/app/repositories/user_repository.py
Normal file
10
backend/app/repositories/user_repository.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import User
|
||||
from .base_repository import BaseRepository
|
||||
from ..schemas import UserSchema, UserCreateSchema
|
||||
|
||||
|
||||
class UserRepository(BaseRepository[User]):
|
||||
def __init__(self, session: AsyncSession):
|
||||
super().__init__(session, model=User)
|
||||
3
backend/app/schemas/__init__.py
Normal file
3
backend/app/schemas/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .base_schemas import BaseSchema
|
||||
from .pagination_schemas import PaginationSchema
|
||||
from .user_schemas import UserSchema, UserCreateSchema
|
||||
0
backend/app/schemas/auth_schemas.py
Normal file
0
backend/app/schemas/auth_schemas.py
Normal file
6
backend/app/schemas/base_schemas.py
Normal file
6
backend/app/schemas/base_schemas.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class BaseSchema(BaseModel):
|
||||
class Config:
|
||||
from_attributes = True
|
||||
17
backend/app/schemas/pagination_schemas.py
Normal file
17
backend/app/schemas/pagination_schemas.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.schemas import BaseSchema
|
||||
|
||||
|
||||
class PaginationSchema[T: BaseSchema](BaseModel):
|
||||
items: List[T]
|
||||
page: int
|
||||
last_page: int
|
||||
first_page: int = 1
|
||||
total_pages: int
|
||||
total_items: int
|
||||
items_by_page: int
|
||||
has_next_page: bool
|
||||
has_prev_page: bool
|
||||
27
backend/app/schemas/user_schemas.py
Normal file
27
backend/app/schemas/user_schemas.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from pydantic import Field, EmailStr
|
||||
|
||||
from app.schemas import BaseSchema
|
||||
|
||||
|
||||
class UserCreateSchema(BaseSchema):
|
||||
name: str = Field(description="Имя")
|
||||
surname: str = Field(description="Фамилия")
|
||||
patronymic: str | None = Field(description="Отчество", default=None)
|
||||
email: EmailStr = Field(description="Адрес электронной почты")
|
||||
password: str = Field(description="Пароль")
|
||||
|
||||
|
||||
class UserUpdateSchema(BaseSchema):
|
||||
name: str | None = Field(description="Имя", default=None)
|
||||
surname: str | None = Field(description="Фамилия", default=None)
|
||||
patronymic: str | None = Field(description="Отчество", default=None)
|
||||
email: EmailStr | None = Field(description="Адрес электронной почты", default=None)
|
||||
password: str | None = Field(description="Пароль", default=None)
|
||||
|
||||
|
||||
class UserSchema(BaseSchema):
|
||||
id: int
|
||||
name: str = Field(description="Имя")
|
||||
surname: str = Field(description="Фамилия")
|
||||
patronymic: str | None = Field(description="Отчество", default=None)
|
||||
email: EmailStr = Field(description="Адрес электронной почты")
|
||||
2
backend/app/services/__init__.py
Normal file
2
backend/app/services/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from .base_service import BaseService
|
||||
from .user_service import UserService
|
||||
0
backend/app/services/auth_service.py
Normal file
0
backend/app/services/auth_service.py
Normal file
28
backend/app/services/user_service.py
Normal file
28
backend/app/services/user_service.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import User
|
||||
from app.repositories import UserRepository
|
||||
from app.schemas import UserCreateSchema, UserSchema
|
||||
|
||||
|
||||
class UserService:
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.__session = session
|
||||
self.__user_repository = UserRepository(session)
|
||||
|
||||
async def get_user_by_id(self, user_id: int) -> User:
|
||||
user = await self.__user_repository.get(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404)
|
||||
return user
|
||||
|
||||
async def create_user(self, user_data: UserCreateSchema) -> User:
|
||||
user = User(**user_data.model_dump(exclude_unset=True))
|
||||
await self.__user_repository.add(user_data)
|
||||
|
||||
async def update_user(self, user_id: int, user_data: UserSchema) -> User:
|
||||
pass
|
||||
|
||||
async def delete_user(self, user_id: int):
|
||||
pass
|
||||
1
backend/app/utils/__init__.py
Normal file
1
backend/app/utils/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .database import async_session_maker
|
||||
13
backend/app/utils/database.py
Normal file
13
backend/app/utils/database.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
AsyncSession,
|
||||
)
|
||||
|
||||
from app.config import database_url
|
||||
|
||||
engine = create_async_engine(url=database_url)
|
||||
|
||||
async_session_maker = async_sessionmaker(
|
||||
engine, class_=AsyncSession, expire_on_commit=False
|
||||
)
|
||||
0
backend/compose.yml
Normal file
0
backend/compose.yml
Normal file
1
backend/migrations/README
Normal file
1
backend/migrations/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
78
backend/migrations/env.py
Normal file
78
backend/migrations/env.py
Normal file
@@ -0,0 +1,78 @@
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||
|
||||
from app.config import database_url
|
||||
from app.models import AbstractModel
|
||||
|
||||
config = context.config
|
||||
config.set_main_option("sqlalchemy.url", database_url)
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = AbstractModel.metadata
|
||||
|
||||
|
||||
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 do_run_migrations(connection: Connection) -> None:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
|
||||
connectable = async_engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
28
backend/migrations/script.py.mako
Normal file
28
backend/migrations/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"}
|
||||
42
backend/migrations/versions/30688df8a838_.py
Normal file
42
backend/migrations/versions/30688df8a838_.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 30688df8a838
|
||||
Revises:
|
||||
Create Date: 2025-06-17 16:34:26.733662
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '30688df8a838'
|
||||
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('users',
|
||||
sa.Column('name', sa.String(length=50), nullable=False),
|
||||
sa.Column('surname', sa.String(length=50), nullable=False),
|
||||
sa.Column('patronymic', sa.String(length=50), nullable=True),
|
||||
sa.Column('email', sa.String(length=256), nullable=False),
|
||||
sa.Column('password', sa.String(length=256), nullable=False),
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_users_id'), table_name='users')
|
||||
op.drop_table('users')
|
||||
# ### end Alembic commands ###
|
||||
32
backend/migrations/versions/a77a1e42b811_.py
Normal file
32
backend/migrations/versions/a77a1e42b811_.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: a77a1e42b811
|
||||
Revises: 30688df8a838
|
||||
Create Date: 2025-06-17 17:27:50.712571
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'a77a1e42b811'
|
||||
down_revision: Union[str, None] = '30688df8a838'
|
||||
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_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||
# ### end Alembic commands ###
|
||||
BIN
backend/requirements.txt
Normal file
BIN
backend/requirements.txt
Normal file
Binary file not shown.
Reference in New Issue
Block a user