Бд +- подготовили, надеюсь нейронка быстро получится все сделать
This commit is contained in:
parent
03e6dfa97c
commit
96f8e782cc
18
database.py
18
database.py
@ -1,30 +1,26 @@
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
engine = create_async_engine("sqlite+aiosqlite:///tasks.db")
|
engine = create_async_engine("sqlite+aiosqlite:///questions.db")
|
||||||
new_session = async_sessionmaker(engine, expire_on_commit=False)
|
new_session = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
|
|
||||||
|
|
||||||
class Model(DeclarativeBase):
|
class Model(DeclarativeBase):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
class QuestionOrm(Model):
|
||||||
class TaskOrm(Model):
|
__tablename__ = "questions"
|
||||||
__tablename__ = "tasks"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
name: Mapped[str]
|
id_user: Mapped[int]
|
||||||
description: Mapped[Optional[str]]
|
type_question: Mapped[bool]
|
||||||
|
question: Mapped[str]
|
||||||
|
answer: Mapped[Optional[str]]
|
||||||
|
|
||||||
async def create_tables():
|
async def create_tables():
|
||||||
# https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#synopsis-core
|
|
||||||
async with engine.begin() as conn:
|
async with engine.begin() as conn:
|
||||||
await conn.run_sync(Model.metadata.create_all)
|
await conn.run_sync(Model.metadata.create_all)
|
||||||
|
|
||||||
|
|
||||||
async def delete_tables():
|
async def delete_tables():
|
||||||
async with engine.begin() as conn:
|
async with engine.begin() as conn:
|
||||||
await conn.run_sync(Model.metadata.drop_all)
|
await conn.run_sync(Model.metadata.drop_all)
|
||||||
|
16
main.py
16
main.py
@ -1,20 +1,22 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
import logging
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
from database import create_tables, delete_tables
|
from database import create_tables, delete_tables
|
||||||
from router import router as tasks_router
|
from router import router as questions_router
|
||||||
|
|
||||||
|
# Настройка логирования
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
await delete_tables()
|
await delete_tables()
|
||||||
print("База очищена")
|
logger.info("База данных очищена")
|
||||||
await create_tables()
|
await create_tables()
|
||||||
print("База готова к работе")
|
logger.info("База данных готова к работе")
|
||||||
yield
|
yield
|
||||||
print("Выключение")
|
logger.info("Выключение")
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(lifespan=lifespan)
|
||||||
app.include_router(tasks_router)
|
app.include_router(questions_router)
|
||||||
|
@ -1,26 +1,24 @@
|
|||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from database import new_session, TaskOrm
|
from database import new_session, QuestionOrm
|
||||||
from schemas import STaskAdd, STask
|
from schemas import SQuestionAdd, SQuestion
|
||||||
|
|
||||||
|
class QuestionRepository:
|
||||||
class TaskRepository:
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def add_one(cls, data: STaskAdd) -> int:
|
async def add_one(cls, data: SQuestionAdd) -> int:
|
||||||
async with new_session() as session:
|
async with new_session() as session:
|
||||||
task_dict = data.model_dump()
|
question_dict = data.model_dump()
|
||||||
|
question = QuestionOrm(**question_dict)
|
||||||
task = TaskOrm(**task_dict)
|
session.add(question)
|
||||||
session.add(task)
|
|
||||||
await session.flush()
|
await session.flush()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return task.id
|
return question.id
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def find_all(cls) -> list[STask]:
|
async def find_all(cls) -> list[SQuestion]:
|
||||||
async with new_session() as session:
|
async with new_session() as session:
|
||||||
query = select(TaskOrm)
|
query = select(QuestionOrm)
|
||||||
result = await session.execute(query)
|
result = await session.execute(query)
|
||||||
task_models = result.scalars().all()
|
question_models = result.scalars().all()
|
||||||
task_schemas = [STask.model_validate(task_model) for task_model in task_models]
|
question_schemas = [SQuestion.model_validate(question_model) for question_model in question_models]
|
||||||
return task_schemas
|
return question_schemas
|
||||||
|
27
router.py
27
router.py
@ -1,25 +1,22 @@
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
from repository import TaskRepository
|
from repository import QuestionRepository
|
||||||
from schemas import STaskAdd, STask, STaskId
|
from schemas import SQuestionAdd, SQuestion, SQuestionId
|
||||||
|
|
||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/tasks",
|
prefix="/questions",
|
||||||
tags=["Таски"],
|
tags=["Questions"],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("")
|
@router.post("")
|
||||||
async def add_task(
|
async def add_question(
|
||||||
task: Annotated[STaskAdd, Depends()],
|
question: Annotated[SQuestionAdd, Depends()],
|
||||||
) -> STaskId:
|
) -> SQuestionId:
|
||||||
task_id = await TaskRepository.add_one(task)
|
question_id = await QuestionRepository.add_one(question)
|
||||||
return {"ok": True, "task_id": task_id}
|
return {"ok": True, "question_id": question_id}
|
||||||
|
|
||||||
|
|
||||||
@router.get("")
|
@router.get("")
|
||||||
async def get_tasks() -> list[STask]:
|
async def get_questions() -> list[SQuestion]:
|
||||||
tasks = await TaskRepository.find_all()
|
questions = await QuestionRepository.find_all()
|
||||||
return tasks
|
return questions
|
||||||
|
18
schemas.py
18
schemas.py
@ -1,19 +1,17 @@
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
class SQuestionAdd(BaseModel):
|
||||||
|
id_user: int
|
||||||
|
type_question: bool
|
||||||
|
question: str
|
||||||
|
|
||||||
class STaskAdd(BaseModel):
|
class SQuestion(SQuestionAdd):
|
||||||
name: str
|
|
||||||
description: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class STask(STaskAdd):
|
|
||||||
id: int
|
id: int
|
||||||
|
answer: Optional[str] = None
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
class SQuestionId(BaseModel):
|
||||||
class STaskId(BaseModel):
|
|
||||||
ok: bool = True
|
ok: bool = True
|
||||||
task_id: int
|
question_id: int
|
||||||
|
Loading…
Reference in New Issue
Block a user