Compare commits

..

No commits in common. "ee709a489ee927b30b65a580c1d7d7a3be46b8db" and "f72c6fe4d7af794b95b1899a21e6b6af904ffc9b" have entirely different histories.

12 changed files with 95 additions and 143 deletions

View File

@ -6,20 +6,43 @@ from fastfood.routers.dish import router as dish_router
from fastfood.routers.menu import router as menu_router from fastfood.routers.menu import router as menu_router
from fastfood.routers.submenu import router as submenu_router from fastfood.routers.submenu import router as submenu_router
tags_metadata = [
{
'name': 'menu',
'description': 'Операции с меню.',
},
{
'name': 'submenu',
'description': 'Подменю и работа с ним',
},
{'name': 'dish', 'description': 'Блюда и работа с ними'},
]
def create_app() -> FastAPI:
def create_app(redis=None) -> FastAPI:
""" """
Фабрика FastAPI. Фабрика FastAPI.
""" """
app = FastAPI() with open('openapi.json') as f:
js = json.load(f)
app = FastAPI(
title=js['info']['title'],
description=js['info']['description'],
version=js['info']['version'],
contact={
'name': 'Sergey Vanyushkin',
'url': 'http://pi3c.ru',
'email': 'pi3c@yandex.ru',
},
license_info={
'name': 'MIT license',
'url': 'https://mit-license.org/',
},
openapi_tags=tags_metadata,
)
app.include_router(menu_router) app.include_router(menu_router)
app.include_router(submenu_router) app.include_router(submenu_router)
app.include_router(dish_router) app.include_router(dish_router)
def custom_openapi():
with open('openapi.json') as openapi:
return json.load(openapi)
app.openapi = custom_openapi
return app return app

View File

@ -10,7 +10,7 @@ from fastfood.schemas import Dish_db
class DishRepository: class DishRepository:
def __init__(self, session: AsyncSession = Depends(get_async_session)) -> None: def __init__(self, session: AsyncSession = Depends(get_async_session)):
self.db = session self.db = session
async def get_dishes(self, menu_id: UUID, submenu_id: UUID) -> list[Dish]: async def get_dishes(self, menu_id: UUID, submenu_id: UUID) -> list[Dish]:
@ -49,20 +49,21 @@ class DishRepository:
submenu_id: UUID, submenu_id: UUID,
dish_id: UUID, dish_id: UUID,
dish_data: Dish_db, dish_data: Dish_db,
) -> Dish | None: ) -> Dish:
query = update(Dish).where(Dish.id == dish_id).values(**dish_data.model_dump()) query = update(Dish).where(Dish.id == dish_id).values(**dish_data.model_dump())
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
qr = select(Dish).where(Dish.id == dish_id) qr = select(Dish).where(Dish.id == dish_id)
updated_submenu = await self.db.execute(qr) updated_submenu = await self.db.execute(qr)
return updated_submenu.scalar_one_or_none() return updated_submenu.scalars().one()
async def delete_dish_item( async def delete_dish_item(
self, self,
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
dish_id: UUID, dish_id: UUID,
) -> None: ) -> int:
query = delete(Dish).where(Dish.id == dish_id) query = delete(Dish).where(Dish.id == dish_id)
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
return 200

View File

@ -11,7 +11,7 @@ from fastfood.models import Dish, Menu, SubMenu
class MenuRepository: class MenuRepository:
def __init__(self, session: AsyncSession = Depends(get_async_session)) -> None: def __init__(self, session: AsyncSession = Depends(get_async_session)):
self.db = session self.db = session
async def get_menus(self) -> list[Menu]: async def get_menus(self) -> list[Menu]:
@ -44,21 +44,23 @@ class MenuRepository:
) )
menu = await self.db.execute(query) menu = await self.db.execute(query)
menu = menu.scalars().one_or_none() menu = menu.scalars().one_or_none()
if menu is None:
return None
return menu return menu
async def update_menu_item( async def update_menu_item(
self, self,
menu_id: UUID, menu_id: UUID,
menu: schemas.MenuBase, menu: schemas.MenuBase,
) -> Menu | None: ) -> Menu:
query = update(Menu).where(Menu.id == menu_id).values(**menu.model_dump()) query = update(Menu).where(Menu.id == menu_id).values(**menu.model_dump())
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
qr = select(Menu).where(Menu.id == menu_id) qr = select(Menu).where(Menu.id == menu_id)
updated_menu = await self.db.execute(qr) updated_menu = await self.db.execute(qr)
return updated_menu.scalar_one_or_none() return updated_menu.scalar_one()
async def delete_menu_item(self, menu_id: UUID) -> None: async def delete_menu_item(self, menu_id: UUID):
query = delete(Menu).where(Menu.id == menu_id) query = delete(Menu).where(Menu.id == menu_id)
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()

View File

@ -31,7 +31,7 @@ class RedisRepository:
pool: redis.Redis = Depends(get_redis_pool), pool: redis.Redis = Depends(get_redis_pool),
) -> None: ) -> None:
self.pool = pool self.pool = pool
self.ttl = 1800 self.ttl = 2
async def get(self, key: str) -> Any | None: async def get(self, key: str) -> Any | None:
data = await self.pool.get(key) data = await self.pool.get(key)

View File

@ -11,7 +11,7 @@ from fastfood.schemas import MenuBase
class SubMenuRepository: class SubMenuRepository:
def __init__(self, session: AsyncSession = Depends(get_async_session)) -> None: def __init__(self, session: AsyncSession = Depends(get_async_session)):
self.db = session self.db = session
async def get_submenus(self, menu_id: UUID) -> list[SubMenu]: async def get_submenus(self, menu_id: UUID) -> list[SubMenu]:
@ -52,6 +52,8 @@ class SubMenuRepository:
) )
submenu = await self.db.execute(query) submenu = await self.db.execute(query)
submenu = submenu.scalars().one_or_none() submenu = submenu.scalars().one_or_none()
if submenu is None:
return None
return submenu return submenu
async def update_submenu_item( async def update_submenu_item(
@ -59,7 +61,7 @@ class SubMenuRepository:
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
submenu_data: MenuBase, submenu_data: MenuBase,
) -> SubMenu | None: ) -> SubMenu:
query = ( query = (
update(SubMenu) update(SubMenu)
.where(SubMenu.id == submenu_id) .where(SubMenu.id == submenu_id)
@ -69,11 +71,12 @@ class SubMenuRepository:
await self.db.commit() await self.db.commit()
qr = select(SubMenu).where(SubMenu.id == submenu_id) qr = select(SubMenu).where(SubMenu.id == submenu_id)
updated_submenu = await self.db.execute(qr) updated_submenu = await self.db.execute(qr)
return updated_submenu.scalar_one_or_none() return updated_submenu.scalar_one()
async def delete_submenu_item(self, menu_id: UUID, submenu_id: UUID) -> None: async def delete_submenu_item(self, menu_id: UUID, submenu_id: UUID) -> int:
query = delete(SubMenu).where( query = delete(SubMenu).where(
SubMenu.id == submenu_id, SubMenu.id == submenu_id,
) )
await self.db.execute(query) await self.db.execute(query)
await self.db.commit() await self.db.commit()
return 200

View File

@ -11,10 +11,7 @@ router = APIRouter(
) )
@router.get( @router.get('/', response_model=list[Dish])
'/',
response_model=list[Dish],
)
async def get_dishes( async def get_dishes(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
@ -25,18 +22,14 @@ async def get_dishes(
return result return result
@router.post( @router.post('/', status_code=201, response_model=Dish)
'/',
status_code=201,
response_model=Dish,
)
async def create_dish( async def create_dish(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
dish_data: DishBase, dish_data: DishBase,
dish: DishService = Depends(), dish: DishService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> Dish: ):
return await dish.create_dish( return await dish.create_dish(
menu_id, menu_id,
submenu_id, submenu_id,
@ -44,34 +37,25 @@ async def create_dish(
) )
@router.get( @router.get('/{dish_id}', response_model=Dish)
'/{dish_id}',
response_model=Dish,
)
async def get_dish( async def get_dish(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
dish_id: UUID, dish_id: UUID,
dish: DishService = Depends(), dish: DishService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> Dish | None: ):
result = await dish.read_dish( result = await dish.read_dish(
menu_id, menu_id,
submenu_id, submenu_id,
dish_id, dish_id,
) )
if not result: if not result:
raise HTTPException( raise HTTPException(status_code=404, detail='dish not found')
status_code=404,
detail=f'Блюдо c UUID={dish_id} не существует, доступ невозможен',
)
return result return result
@router.patch( @router.patch('/{dish_id}', response_model=Dish)
'/{dish_id}',
response_model=Dish,
)
async def update_dish( async def update_dish(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
@ -79,29 +63,22 @@ async def update_dish(
dish_data: DishBase, dish_data: DishBase,
dish: DishService = Depends(), dish: DishService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> Dish: ):
result = await dish.update_dish( result = await dish.update_dish(
menu_id, menu_id,
submenu_id, submenu_id,
dish_id, dish_id,
dish_data, dish_data,
) )
if not result:
raise HTTPException(
status_code=404,
detail=f'Блюдо c UUID={dish_id} не существует, обновление невозможно',
)
return result return result
@router.delete( @router.delete('/{dish_id}')
'/{dish_id}',
)
async def delete_dish( async def delete_dish(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
dish_id: UUID, dish_id: UUID,
dish: DishService = Depends(), dish: DishService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> None: ):
await dish.del_dish(menu_id, submenu_id, dish_id) await dish.del_dish(menu_id, submenu_id, dish_id)

View File

@ -11,80 +11,54 @@ router = APIRouter(
) )
@router.get( @router.get('/', response_model=list[MenuRead])
'/',
status_code=200,
response_model=list[MenuRead],
)
async def get_menus( async def get_menus(
menu: MenuService = Depends(), menu: MenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> list[MenuRead]: ):
return await menu.read_menus() return await menu.read_menus()
@router.post( @router.post('/', status_code=201, response_model=MenuRead)
'/',
status_code=201,
response_model=MenuRead,
)
async def add_menu( async def add_menu(
menu: MenuBase, menu: MenuBase,
responce: MenuService = Depends(), responce: MenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> MenuRead: ):
return await responce.create_menu(menu) return await responce.create_menu(menu)
@router.get( @router.get('/{menu_id}', response_model=MenuRead)
'/{menu_id}',
response_model=MenuRead,
)
async def get_menu( async def get_menu(
menu_id: UUID, menu_id: UUID,
responce: MenuService = Depends(), responce: MenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> MenuRead: ):
result = await responce.read_menu(menu_id=menu_id) result = await responce.read_menu(menu_id=menu_id)
if not result: if not result:
raise HTTPException( raise HTTPException(status_code=404, detail='menu not found')
status_code=404,
detail=f'Меню c UUID={menu_id} не существует, доступ невозможен',
)
return result return result
@router.patch( @router.patch('/{menu_id}', response_model=MenuRead)
'/{menu_id}',
response_model=MenuRead,
)
async def update_menu( async def update_menu(
menu_id: UUID, menu_id: UUID,
menu: MenuBase, menu: MenuBase,
responce: MenuService = Depends(), responce: MenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> MenuRead: ):
result = await responce.update_menu( result = await responce.update_menu(
menu_id=menu_id, menu_id=menu_id,
menu_data=menu, menu_data=menu,
) )
if not result:
raise HTTPException(
status_code=404,
detail=f'Меню c UUID={menu_id} не существует, Обновление невозможно',
)
return result return result
@router.delete( @router.delete('/{menu_id}')
'/{menu_id}',
status_code=200,
)
async def delete_menu( async def delete_menu(
menu_id: UUID, menu_id: UUID,
menu: MenuService = Depends(), menu: MenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> None: ):
await menu.del_menu(menu_id) await menu.del_menu(menu_id)

View File

@ -11,30 +11,23 @@ router = APIRouter(
) )
@router.get( @router.get('/', response_model=list[SubMenuRead])
'/',
response_model=list[SubMenuRead],
)
async def get_submenus( async def get_submenus(
menu_id: UUID, menu_id: UUID,
submenu: SubmenuService = Depends(), submenu: SubmenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> list[SubMenuRead]: ):
result = await submenu.read_submenus(menu_id=menu_id) result = await submenu.read_submenus(menu_id=menu_id)
return result return result
@router.post( @router.post('/', status_code=201, response_model=SubMenuRead)
'/',
status_code=201,
response_model=SubMenuRead,
)
async def create_submenu_item( async def create_submenu_item(
menu_id: UUID, menu_id: UUID,
submenu_data: MenuBase, submenu_data: MenuBase,
submenu: SubmenuService = Depends(), submenu: SubmenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> SubMenuRead: ):
result = await submenu.create_submenu( result = await submenu.create_submenu(
menu_id=menu_id, menu_id=menu_id,
submenu_data=submenu_data, submenu_data=submenu_data,
@ -42,25 +35,19 @@ async def create_submenu_item(
return result return result
@router.get( @router.get('/{submenu_id}', response_model=SubMenuRead)
'/{submenu_id}',
response_model=SubMenuRead,
)
async def get_submenu( async def get_submenu(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
submenu: SubmenuService = Depends(), submenu: SubmenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> SubMenuRead: ):
result = await submenu.read_menu( result = await submenu.read_menu(
menu_id=menu_id, menu_id=menu_id,
submenu_id=submenu_id, submenu_id=submenu_id,
) )
if not result: if not result:
raise HTTPException( raise HTTPException(status_code=404, detail='submenu not found')
status_code=404,
detail=f'Подменю c UUID={submenu_id} не существует, доступ невозможен',
)
return result return result
@ -74,28 +61,20 @@ async def update_submenu(
submenu_data: MenuBase, submenu_data: MenuBase,
submenu: SubmenuService = Depends(), submenu: SubmenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> SubMenuRead: ):
result = await submenu.update_submenu( result = await submenu.update_submenu(
menu_id=menu_id, menu_id=menu_id,
submenu_id=submenu_id, submenu_id=submenu_id,
submenu_data=submenu_data, submenu_data=submenu_data,
) )
if not result:
raise HTTPException(
status_code=404,
detail=f'Gjlvеню c UUID={submenu_id} не существует, обновление невозможно',
)
return result return result
@router.delete( @router.delete('/{submenu_id}')
'/{submenu_id}',
)
async def delete_submenu( async def delete_submenu(
menu_id: UUID, menu_id: UUID,
submenu_id: UUID, submenu_id: UUID,
submenu: SubmenuService = Depends(), submenu: SubmenuService = Depends(),
background_tasks: BackgroundTasks = BackgroundTasks(), background_tasks: BackgroundTasks = BackgroundTasks(),
) -> None: ):
await submenu.del_menu(menu_id=menu_id, submenu_id=submenu_id) await submenu.del_menu(menu_id=menu_id, submenu_id=submenu_id)

View File

@ -103,19 +103,14 @@ class DishService:
async def update_dish( async def update_dish(
self, menu_id: UUID, submenu_id: UUID, dish_id, dish_data: DishBase self, menu_id: UUID, submenu_id: UUID, dish_id, dish_data: DishBase
) -> Dish | None: ) -> Dish:
dish_db = Dish_db(**dish_data.model_dump()) dish_db = Dish_db(**dish_data.model_dump())
data = await self.dish_repo.update_dish_item( data = await self.dish_repo.update_dish_item(
menu_id, submenu_id, dish_id, dish_db menu_id, submenu_id, dish_id, dish_db
) )
if data is None:
return None
dish = data.__dict__ dish = data.__dict__
dish['price'] = str(dish['price']) dish['price'] = str(dish['price'])
dish = Dish(**dish) dish = Dish(**dish)
await self.cache.set( await self.cache.set(
self.key( self.key(
'dish', 'dish',
@ -130,11 +125,13 @@ class DishService:
return dish return dish
async def del_dish(self, menu_id: UUID, submenu_id: UUID, dish_id: UUID) -> None: async def del_dish(self, menu_id: UUID, submenu_id: UUID, dish_id: UUID) -> int:
await self.dish_repo.delete_dish_item( response = await self.dish_repo.delete_dish_item(
menu_id, menu_id,
submenu_id, submenu_id,
dish_id, dish_id,
) )
await self.cache.delete(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.delete(key=str(menu_id), bg_task=self.bg_tasks)
await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks)
return response

View File

@ -87,10 +87,8 @@ class MenuService:
) )
return menu return menu
async def update_menu(self, menu_id: UUID, menu_data) -> MenuRead | None: async def update_menu(self, menu_id: UUID, menu_data) -> MenuRead:
data = await self.menu_repo.update_menu_item(menu_id, menu_data) data = await self.menu_repo.update_menu_item(menu_id, menu_data)
if data is None:
return None
menu = data.__dict__ menu = data.__dict__
menu = {k: v for k, v in menu.items() if not k.startswith('_')} menu = {k: v for k, v in menu.items() if not k.startswith('_')}
dishes_conter = 0 dishes_conter = 0
@ -106,7 +104,8 @@ class MenuService:
await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks)
return menu return menu
async def del_menu(self, menu_id: UUID) -> None: async def del_menu(self, menu_id: UUID):
await self.menu_repo.delete_menu_item(menu_id) data = await self.menu_repo.delete_menu_item(menu_id)
await self.cache.delete(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.delete(key=str(menu_id), bg_task=self.bg_tasks)
await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks)
return data

View File

@ -89,18 +89,14 @@ class SubmenuService:
async def update_submenu( async def update_submenu(
self, menu_id: UUID, submenu_id: UUID, submenu_data: MenuBase self, menu_id: UUID, submenu_id: UUID, submenu_data: MenuBase
) -> SubMenuRead | None: ) -> SubMenuRead:
data = await self.submenu_repo.update_submenu_item( data = await self.submenu_repo.update_submenu_item(
menu_id, submenu_id, submenu_data menu_id, submenu_id, submenu_data
) )
if data is None:
return None
submenu = data.__dict__ submenu = data.__dict__
submenu = {k: v for k, v in submenu.items() if not k.startswith('_')} submenu = {k: v for k, v in submenu.items() if not k.startswith('_')}
submenu['dishes_count'] = len(submenu.pop('dishes')) submenu['dishes_count'] = len(submenu.pop('dishes'))
submenu = SubMenuRead(**submenu) submenu = SubMenuRead(**submenu)
await self.cache.set( await self.cache.set(
self.key('submenu', menu_id=str(menu_id), submenu_id=str(submenu_id)), self.key('submenu', menu_id=str(menu_id), submenu_id=str(submenu_id)),
submenu, submenu,
@ -110,8 +106,8 @@ class SubmenuService:
return submenu return submenu
async def del_menu(self, menu_id: UUID, submenu_id: UUID) -> None: async def del_menu(self, menu_id: UUID, submenu_id: UUID) -> int:
await self.submenu_repo.delete_submenu_item(menu_id, submenu_id) code = await self.submenu_repo.delete_submenu_item(menu_id, submenu_id)
await self.cache.delete( await self.cache.delete(
key=self.key( key=self.key(
'submenu', 'submenu',
@ -121,3 +117,4 @@ class SubmenuService:
bg_task=self.bg_tasks, bg_task=self.bg_tasks,
) )
await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks) await self.cache.invalidate(key=str(menu_id), bg_task=self.bg_tasks)
return code

File diff suppressed because one or more lines are too long