|
| 1 | +from fastapi import APIRouter, Depends, HTTPException, status |
| 2 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 3 | + |
| 4 | +from app.core.database import get_session |
| 5 | +from app.crud.words import CRUDWord |
| 6 | +from app.schemas.words import WordCreateSchema, WordReadSchema |
| 7 | + |
| 8 | +word_router = APIRouter( |
| 9 | + prefix="/words", |
| 10 | + tags=[ |
| 11 | + "Слова", |
| 12 | + ], |
| 13 | +) |
| 14 | + |
| 15 | +word_crud = CRUDWord() |
| 16 | + |
| 17 | + |
| 18 | +@word_router.post( |
| 19 | + "", |
| 20 | + response_model=WordReadSchema, |
| 21 | + summary="Добавление слова", |
| 22 | +) |
| 23 | +async def add_word( |
| 24 | + word: WordCreateSchema, session: AsyncSession = Depends(get_session) |
| 25 | +) -> WordReadSchema: |
| 26 | + try: |
| 27 | + add_word = await word_crud.create_word(word, session) |
| 28 | + return add_word |
| 29 | + except Exception as e: |
| 30 | + raise e |
| 31 | + |
| 32 | + |
| 33 | +@word_router.get( |
| 34 | + "/all", |
| 35 | + response_model=list[WordReadSchema], |
| 36 | + summary="Получение списка всех слов", |
| 37 | +) |
| 38 | +async def get_all_words( |
| 39 | + session: AsyncSession = Depends(get_session), |
| 40 | +) -> list[WordReadSchema]: |
| 41 | + try: |
| 42 | + words = await word_crud.get_all_words(session) |
| 43 | + if not words: |
| 44 | + raise HTTPException( |
| 45 | + status_code=status.HTTP_404_NOT_FOUND, |
| 46 | + detail="Список слов отсутсттвует", |
| 47 | + ) |
| 48 | + return words |
| 49 | + except Exception as e: |
| 50 | + raise e |
| 51 | + |
| 52 | + |
| 53 | +@word_router.get( |
| 54 | + "/{word}", response_model=WordReadSchema, summary="Получение слова" |
| 55 | +) |
| 56 | +async def get_word( |
| 57 | + word: str, session: AsyncSession = Depends(get_session) |
| 58 | +) -> WordReadSchema: |
| 59 | + try: |
| 60 | + word = word.lower() |
| 61 | + find_word = await word_crud.get_word(word, session) |
| 62 | + if not find_word: |
| 63 | + raise HTTPException( |
| 64 | + status_code=status.HTTP_404_NOT_FOUND, |
| 65 | + detail="Слово не найдено", |
| 66 | + ) |
| 67 | + return find_word |
| 68 | + except Exception as e: |
| 69 | + raise e |
0 commit comments