Гений чел с ютуба, посмотрим получится или нет
This commit is contained in:
parent
a28be450db
commit
9a6c995ed7
3
.dockeringore
Normal file
3
.dockeringore
Normal file
@ -0,0 +1,3 @@
|
||||
venv
|
||||
Dockerfile
|
||||
tasks.db
|
166
.gitignore
vendored
166
.gitignore
vendored
@ -1,162 +1,4 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$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
|
||||
|
||||
# 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
|
||||
|
||||
# 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/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# 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
|
||||
.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/
|
||||
|
||||
venv
|
||||
tasks.db
|
||||
.idea
|
||||
__pycache__
|
14
Dockerfile
Normal file
14
Dockerfile
Normal file
@ -0,0 +1,14 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
COPY ../../../../../AppData/Local/Temp .
|
||||
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
|
||||
# Для запуска введите две команды:
|
||||
# docker build . --tag fastapi_app
|
||||
# docker run -p 80:80 fastapi_app
|
||||
|
||||
# Или одной командой
|
||||
# docker build . --tag fastapi_app && docker run -p 80:80 fastapi_app
|
30
database.py
Normal file
30
database.py
Normal file
@ -0,0 +1,30 @@
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///tasks.db")
|
||||
new_session = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
class Model(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class TaskOrm(Model):
|
||||
__tablename__ = "tasks"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str]
|
||||
description: Mapped[Optional[str]]
|
||||
|
||||
|
||||
async def create_tables():
|
||||
# https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#synopsis-core
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Model.metadata.create_all)
|
||||
|
||||
|
||||
async def delete_tables():
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Model.metadata.drop_all)
|
20
main.py
Normal file
20
main.py
Normal file
@ -0,0 +1,20 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from database import create_tables, delete_tables
|
||||
from router import router as tasks_router
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await delete_tables()
|
||||
print("База очищена")
|
||||
await create_tables()
|
||||
print("База готова к работе")
|
||||
yield
|
||||
print("Выключение")
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.include_router(tasks_router)
|
26
repository.py
Normal file
26
repository.py
Normal file
@ -0,0 +1,26 @@
|
||||
from sqlalchemy import select
|
||||
|
||||
from database import new_session, TaskOrm
|
||||
from schemas import STaskAdd, STask
|
||||
|
||||
|
||||
class TaskRepository:
|
||||
@classmethod
|
||||
async def add_one(cls, data: STaskAdd) -> int:
|
||||
async with new_session() as session:
|
||||
task_dict = data.model_dump()
|
||||
|
||||
task = TaskOrm(**task_dict)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
await session.commit()
|
||||
return task.id
|
||||
|
||||
@classmethod
|
||||
async def find_all(cls) -> list[STask]:
|
||||
async with new_session() as session:
|
||||
query = select(TaskOrm)
|
||||
result = await session.execute(query)
|
||||
task_models = result.scalars().all()
|
||||
task_schemas = [STask.model_validate(task_model) for task_model in task_models]
|
||||
return task_schemas
|
BIN
requirements.txt
Normal file
BIN
requirements.txt
Normal file
Binary file not shown.
25
router.py
Normal file
25
router.py
Normal file
@ -0,0 +1,25 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from repository import TaskRepository
|
||||
from schemas import STaskAdd, STask, STaskId
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/tasks",
|
||||
tags=["Таски"],
|
||||
)
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def add_task(
|
||||
task: Annotated[STaskAdd, Depends()],
|
||||
) -> STaskId:
|
||||
task_id = await TaskRepository.add_one(task)
|
||||
return {"ok": True, "task_id": task_id}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_tasks() -> list[STask]:
|
||||
tasks = await TaskRepository.find_all()
|
||||
return tasks
|
19
schemas.py
Normal file
19
schemas.py
Normal file
@ -0,0 +1,19 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class STaskAdd(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class STask(STaskAdd):
|
||||
id: int
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class STaskId(BaseModel):
|
||||
ok: bool = True
|
||||
task_id: int
|
Loading…
Reference in New Issue
Block a user