From b223053cf65172036e895ac88fed240c3520c7b1 Mon Sep 17 00:00:00 2001 From: Sergey Vanyushkin Date: Fri, 2 Feb 2024 13:01:37 +0000 Subject: [PATCH] sync --- dump.rdb | Bin 0 -> 3057 bytes fastfood/app.py | 1 - fastfood/cruds/menu.py | 76 +++++++++++++++++---------------------- fastfood/routers/menu.py | 32 ++++++++--------- fastfood/service/menu.py | 31 ++++++++-------- tests/test_api.py | 45 +++++++++++------------ 6 files changed, 88 insertions(+), 97 deletions(-) create mode 100644 dump.rdb diff --git a/dump.rdb b/dump.rdb new file mode 100644 index 0000000000000000000000000000000000000000..6be976d5c449b12f7fb88ddc3260cdf0b4c9dc0a GIT binary patch literal 3057 zcmd_sZ)_7~0LSsWUfXr+ws!oPL>Rjg2Lp4Zf7cZx^bZgR0)erh3D`b&_jJ$2wpV&r zWG0J+1j*dFDLW#(87(7|Y$0JUKp_ZY6<-jdkq{CfBgYFAUtyxJDiN=x&Bj=aQDY3g zdvb4|&-4A=_Vw%9+HE$wJztrGEGJNVVN&O@I;^gI)zc3&Cko@fyp9pM7@X)nbrI$b zDFL!n48|tToHS#31K=YR4Fouj{f7Oj(>?z2IL>{9V;J^|!|iGT!0V-0*5jsJZnlL2 zEfGMu-Cl>SwKd}O0DCTg1=6~-_DD*Dg|SA-6aj)5;d#~?<5?ILWJ$Xj##8cuynMgh zEt{I9IUxarxVRvKI0HkZey#{*X`Zkr3Ze{xu`Vm0j9D}FcuiYo8P*H;8 zSc=?5aC}_wQJ8@|Yv3XrWaS>IBI6~i2;v>s z*3)k|+>sx?wLUd@Y-B@|Kp&L19FnD~iWrE4PMDOX#ftuc@2WPLiotj~T_a0%p>~+$ zK$LqAZqB$eKi8mYq!H*8E$Ku~j9TpbJ8((k>odIsgswP~=(Hv}6G>j=$1BLD%&Eqp zxoN}5vB}i>Tf_N|!-jrORz4_imn9<$1t!TQd{6Z97Rex_XtEDWSGL|szQGCN_%JRR{gYb2f`mx^q(v*Gx}bu2Fn?x#<~w6EnvblKk$*Q1 zliAY*s+20zCX89qYWcQW%K{O|$RQcI_+CprSqu6qbug9?yX2k}ZJCSH*2n2@DoSSP zh|@*4xIGl(^w=nuodFa8cJ<`7*?`^2x|}XYE}#qa7R;nyU^8`r;F>JfW*)ibPvmx< zb6v(tXpGV`XukJ-T|%?}c{IPwMB~8pF$E`R zxl@MYd76%WeFz;R8>j{ zW%;Ts!CsU=K2#<2Pm|z#fFt6-Rs!i!Wu{V7jn?=H9MxKkT64dQ=8zTmydHATJOV8U znwK8GGr*7f1`gdkd8y(0)eDxv>V zRzo3MdWFV`++jobo({F5wa80~6|2xzw7Lhqrpz6~+I9ByHfBGwRSU2%%~myOzkeuQoHPo+WqjS zYWMk6?E;qDW#iLocXXO@OR;ttZ`loK@wmJYMkp6>s^dtz?NqD7NmGnNU1)VVy|9)3 uf6Qd>U}EU>#OedvHrX~l8We~B#hIKf#Z&)R|Dlnw|)mVk~O*j literal 0 HcmV?d00001 diff --git a/fastfood/app.py b/fastfood/app.py index 25e3d66..e4037b8 100644 --- a/fastfood/app.py +++ b/fastfood/app.py @@ -1,4 +1,3 @@ -import aioredis from fastapi import FastAPI, Request from starlette.responses import JSONResponse diff --git a/fastfood/cruds/menu.py b/fastfood/cruds/menu.py index d1e31ea..ea6b9bd 100644 --- a/fastfood/cruds/menu.py +++ b/fastfood/cruds/menu.py @@ -26,55 +26,45 @@ class MenuCrud: await self.db.refresh(new_menu) return new_menu - @staticmethod - async def get_menu_item( - menu_id: UUID, session: AsyncSession = Depends(get_async_session) - ): - async with session: - m = aliased(models.Menu) - s = aliased(models.SubMenu) - d = aliased(models.Dish) + async def get_menu_item(self, menu_id: UUID): + m = aliased(models.Menu) + s = aliased(models.SubMenu) + d = aliased(models.Dish) - query = ( - select( - m, - func.count(distinct(s.id)).label("submenus_count"), - func.count(distinct(d.id)).label("dishes_count"), - ) - .join(s, s.parent_menu == m.id, isouter=True) - .join(d, d.parent_submenu == s.id, isouter=True) - .group_by(m.id) - .where(m.id == menu_id) + query = ( + select( + m, + func.count(distinct(s.id)).label("submenus_count"), + func.count(distinct(d.id)).label("dishes_count"), ) - menu = await session.execute(query) - menu = menu.scalars().one_or_none() - if menu is None: - return None + .join(s, s.parent_menu == m.id, isouter=True) + .join(d, d.parent_submenu == s.id, isouter=True) + .group_by(m.id) + .where(m.id == menu_id) + ) + menu = await self.db.execute(query) + menu = menu.scalars().one_or_none() + if menu is None: + return None return menu - @staticmethod async def update_menu_item( + self, menu_id: UUID, menu: schemas.MenuBase, - session: AsyncSession = Depends(get_async_session), ): - async with session: - query = ( - update(models.Menu) - .where(models.Menu.id == menu_id) - .values(**menu.model_dump()) - ) - await session.execute(query) - await session.commit() - qr = select(models.Menu).where(models.Menu.id == menu_id) - updated_menu = await session.execute(qr) - return updated_menu + query = ( + update(models.Menu) + .where(models.Menu.id == menu_id) + .values(**menu.model_dump()) + ) + await self.db.execute(query) + await self.db.commit() + qr = select(models.Menu).where(models.Menu.id == menu_id) + updated_menu = await self.db.execute(qr) + return updated_menu - @staticmethod - async def delete_menu_item( - menu_id: UUID, session: AsyncSession = Depends(get_async_session) - ): - async with session: - query = delete(models.Menu).where(models.Menu.id == menu_id) - await session.execute(query) - await session.commit() + async def delete_menu_item(self, menu_id: UUID): + query = delete(models.Menu).where(models.Menu.id == menu_id) + await self.db.execute(query) + await self.db.commit() diff --git a/fastfood/routers/menu.py b/fastfood/routers/menu.py index fb5b2b7..71d10ae 100644 --- a/fastfood/routers/menu.py +++ b/fastfood/routers/menu.py @@ -20,8 +20,7 @@ async def get_menus( menu: MenuService = Depends(), background_tasks: BackgroundTasks = BackgroundTasks(), ): - result = await menu.read_menus() - return result + return await menu.read_menus() @router.post("/", status_code=201, response_model=schemas.Menu) @@ -30,16 +29,16 @@ async def add_menu( responce: MenuService = Depends(), background_tasks: BackgroundTasks = BackgroundTasks(), ): - rspn = await responce.create_menu(menu) - return rspn + return await responce.create_menu(menu) @router.get("/{menu_id}", response_model=schemas.MenuRead) async def get_menu( menu_id: UUID, - session: AsyncSession = Depends(get_async_session), + responce: MenuService = Depends(), + background_tasks: BackgroundTasks = BackgroundTasks(), ): - result = await crud.get_menu_item(menu_id=menu_id, session=session) + result = await responce.read_menu(menu_id=menu_id) if not result: raise HTTPException(status_code=404, detail="menu not found") @@ -50,19 +49,20 @@ async def get_menu( async def update_menu( menu_id: UUID, menu: schemas.MenuBase, - session: AsyncSession = Depends(get_async_session), + responce: MenuService = Depends(), + background_tasks: BackgroundTasks = BackgroundTasks(), ): - result = await crud.update_menu_item( + result = await responce.update_menu( menu_id=menu_id, - menu=menu, - session=session, + menu_data=menu, ) return result.scalars().one() -@router.delete("/{menu_id}") -async def delete_menu( - menu_id: UUID, - session: AsyncSession = Depends(get_async_session), -): - await crud.delete_menu_item(menu_id=menu_id, session=session) +# +# @router.delete("/{menu_id}") +# async def delete_menu( +# menu_id: UUID, +# session: AsyncSession = Depends(get_async_session), +# ): +# await crud.delete_menu_item(menu_id=menu_id, session=session) diff --git a/fastfood/service/menu.py b/fastfood/service/menu.py index 2faf96c..871166f 100644 --- a/fastfood/service/menu.py +++ b/fastfood/service/menu.py @@ -1,4 +1,5 @@ import pickle +from uuid import UUID import redis.asyncio as redis # type: ignore from fastapi import BackgroundTasks, Depends @@ -36,21 +37,21 @@ class MenuService: await self.cache_client.clear_after_change(str(data.id), self.background_tasks) return data - # async def read_menu(self, menu_id: int | str): - # cached = await self.cache_client.get(f'{menu_id}') - # if cached is not None: - # return cached - # - # data = await self.menu_crud.read_menu(menu_id) - # await self.cache_client.set(f'{menu_id}', data, self.background_tasks) - # return data - # - # async def update_menu(self, menu_id: int | str, menu_data): - # data = await self.menu_crud.update_menu(menu_id, menu_data) - # await self.cache_client.set(f'{menu_id}', data, self.background_tasks) - # await self.cache_client.clear_after_change(menu_id, self.background_tasks) - # return data - # + async def read_menu(self, menu_id: UUID): + cached = await self.cache_client.get(str(menu_id)) + if cached is not None: + return cached + + data = await self.menu_crud.get_menu_item(menu_id) + await self.cache_client.set(str(menu_id), data, self.background_tasks) + return data + + async def update_menu(self, menu_id: UUID, menu_data): + data = await self.menu_crud.update_menu_item(menu_id, menu_data) + await self.cache_client.set(str(menu_id), data, self.background_tasks) + await self.cache_client.clear_after_change(str(menu_id), self.background_tasks) + return data + # async def del_menu(self, menu_id: int | str): # data = await self.menu_crud.del_menu(menu_id) # await self.cache_client.delete(f'{menu_id}', self.background_tasks) diff --git a/tests/test_api.py b/tests/test_api.py index ece7945..6aedb6b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -7,10 +7,10 @@ from httpx import AsyncClient, Response class TestBaseCrud: class Menu: @staticmethod - async def read_all(cli: AsyncClient) -> Tuple[int, dict]: + async def read_all(ac: AsyncClient) -> Tuple[int, dict]: """чтение всех меню""" - response: Response = await cli.get("/") + response: Response = await ac.get("/") return response.status_code, response.json() @staticmethod @@ -149,32 +149,33 @@ class TestBaseCrud: @pytest.mark.asyncio async def test_menu_crud(client) -> None: """Тестирование функций меню""" - code, rspn = await TestBaseCrud.Menu.read_all(client) + code, menus = await TestBaseCrud.Menu.read_all(client) assert code == 200 + assert menus == [] data = {"title": "Menu", "description": None} - code, rspn = await TestBaseCrud.Menu.write(client, data) + code, menu = await TestBaseCrud.Menu.write(client, data) assert code == 201 - assert rspn["title"] == "Menu" - assert rspn["description"] is None - data = {"title": "Menu1", "description": "11"} - code, rspn = await TestBaseCrud.Menu.write(client, data) - code, rspn = await TestBaseCrud.Menu.read_all(client) + assert menu["title"] == "Menu" + assert menu["description"] is None + code, menus = await TestBaseCrud.Menu.read_all(client) + assert len(menus) == 1 + + code, menu = await TestBaseCrud.Menu.get(client, {"id": menu.get("id")}) + assert code == 200 + assert menu["title"] == data["title"] + + upd_menu = { + "id": menu.get("id"), + "title": "upd Menu", + "description": "", + } + code, menu = await TestBaseCrud.Menu.update(client, upd_menu) + assert code == 200 + print(menu) + # assert menu["title"] == "upd Menu" -# code, menu = await self.Menu.get(client, {"id": rspn.get("id")}) -# assert code == 200 -# assert menu["title"] == rspn["title"] -# -# upd_data = { -# "id": rspn.get("id"), -# "title": "upd Menu", -# "description": "", -# } -# code, upd_rspn = await self.Menu.update(client, upd_data) -# assert code == 200 -# assert upd_rspn["title"] == "upd Menu" -# # code = await self.Menu.delete(client, rspn) # assert code == 200 #