develop
Сергей Ванюшкин 2024-02-02 13:01:37 +00:00
parent 58ecd82bb6
commit b223053cf6
6 changed files with 88 additions and 97 deletions

BIN
dump.rdb Normal file

Binary file not shown.

View File

@ -1,4 +1,3 @@
import aioredis
from fastapi import FastAPI, Request
from starlette.responses import JSONResponse

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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
#