Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refractoring 1 #32

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 0 additions & 96 deletions aciniformes_backend/routes/alert.py

This file was deleted.

2 changes: 0 additions & 2 deletions aciniformes_backend/routes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from aciniformes_backend import __version__
from aciniformes_backend.settings import get_settings

from .alert import router as alert_router
from .fetcher import router as fetcher_router
from .mectric import router as metric_router
from .receiver import router as receiver_router
Expand Down Expand Up @@ -34,7 +33,6 @@
allow_headers=settings.CORS_ALLOW_HEADERS,
)

app.include_router(alert_router, prefix="/alert", tags=["Alert"])
app.include_router(receiver_router, prefix="/receiver", tags=["Receiver"])
app.include_router(fetcher_router, prefix="/fetcher", tags=["Fetcher"])
app.include_router(metric_router, prefix="/metric", tags=["Metric"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не понял нафига его было переносить, а особенно под routes. Пусть может в корне апишки лежит?

File renamed without changes.
54 changes: 33 additions & 21 deletions aciniformes_backend/routes/fetcher.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import logging

import sqlalchemy as sa
from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends
from fastapi.exceptions import HTTPException
from fastapi_sqlalchemy import db
from pydantic import BaseModel, HttpUrl
from pydantic.functional_serializers import PlainSerializer
from starlette import status
from typing_extensions import Annotated

import aciniformes_backend.models as db_models
from aciniformes_backend.models.fetcher import FetcherType
from aciniformes_backend.serivce import FetcherServiceInterface
from aciniformes_backend.serivce import exceptions as exc
from aciniformes_backend.serivce import fetcher_service
from aciniformes_backend.routes import exceptions as exc


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -43,64 +44,75 @@ class GetSchema(BaseModel):


@router.post("", response_model=ResponsePostSchema)
async def create(
def create(
create_schema: CreateSchema,
fetcher: FetcherServiceInterface = Depends(fetcher_service),
_: dict[str] = Depends(UnionAuth(['pinger.fetcher.create'])),
):
"""
Создает новый сборщик метрик.
"""
id_ = await fetcher.create(create_schema.model_dump())
return ResponsePostSchema(**create_schema.model_dump(), id=id_)
q = sa.insert(db_models.Fetcher).values(**create_schema.model_dump()).returning(db_models.Fetcher)
fetcher = db.session.scalar(q)
db.session.flush()
Comment on lines -54 to +56
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему не как во всех апишках?

from db_models import Fetcher

fetcher = Fetcher(**create_schema.model_dump())
q = db.session.add(fetcher)
db.session.flush()

return ResponsePostSchema(**create_schema.model_dump(), id=fetcher.id_)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А чего не из добавленного в БД, а из аргумента функции?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Делается через from_attributes в конфиге ResponsePostSchema



@router.get("")
async def get_all(
fetcher: FetcherServiceInterface = Depends(fetcher_service),
def get_all(
_: dict[str] = Depends(UnionAuth(['pinger.fetcher.read'])),
):
"""
Возвращает все сборщики метрик.
"""
res = await fetcher.get_all()
return res
return list(db.session.scalars(sa.select(db_models.Fetcher)).all())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Какая сложная штука
+непонятно что вернет, где схема?



@router.get("/{id}")
async def get(
def get(
id: int,
fetcher: FetcherServiceInterface = Depends(fetcher_service),
_: dict[str] = Depends(UnionAuth(['pinger.fetcher.read'])),
):
"""Получение одного сборщика метрик по id"""
try:
res = await fetcher.get_by_id(id)
q = sa.select(db_models.Fetcher).where(db_models.Fetcher.id_ == id)
res = db.session.scalar(q)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему ты забираешь скаляр? Это id возвращает же? Одно значение, не объект. Тут бы хотелось видеть атрибуты фетчера

if not res:
raise exc.ObjectNotFound(id)
return res
except exc.ObjectNotFound:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
Comment on lines 82 to 83
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай через Exception handler мб?

return res


@router.patch("/{id}")
async def update(
def update(
id: int,
update_schema: UpdateSchema,
fetcher: FetcherServiceInterface = Depends(fetcher_service),
_: dict[str] = Depends(UnionAuth(['pinger.fetcher.update'])),
):
"""Обновление одного сборщика метрик по id"""
try:
res = await fetcher.update(id, update_schema.model_dump(exclude_unset=True))
q = sa.select(db_models.Fetcher).where(db_models.Fetcher.id_ == id)
res = db.session.scalar(q)
if not res:
raise exc.ObjectNotFound(id)
q = (
sa.update(db_models.Fetcher)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень ORM-way, он скорее предполагает что ты получаешь объект Fetcher (db.session.get(Fetcher, id)), редачишь его и после делаешь flush.

.where(db_models.Fetcher.id_ == id)
.values(**update_schema)
.returning(db_models.Fetcher)
)
res = db.session.execute(q).scalar()
except exc.ObjectNotFound:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
Comment on lines 105 to 106
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exception handler?

return res


@router.delete("/{id}")
async def delete(
def delete(
id: int,
fetcher: FetcherServiceInterface = Depends(fetcher_service),
_: dict[str] = Depends(UnionAuth(['pinger.fetcher.delete'])),
):
"""Удаление одного сборщика метрик по id"""
await fetcher.delete(id)
q = sa.delete(db_models.Fetcher).where(db_models.Fetcher.id_ == id)
db.session.execute(q)
db.session.flush()
32 changes: 17 additions & 15 deletions aciniformes_backend/routes/mectric.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import sqlalchemy as sa
from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends
from fastapi.exceptions import HTTPException
from fastapi_sqlalchemy import db
from pydantic import BaseModel
from starlette import status

from aciniformes_backend.serivce import MetricServiceInterface
from aciniformes_backend.serivce import exceptions as exc
from aciniformes_backend.serivce import metric_service
import aciniformes_backend.models as db_models
from aciniformes_backend.routes import exceptions as exc


class CreateSchema(BaseModel):
Expand All @@ -30,35 +31,36 @@ class GetSchema(BaseModel):


@router.post("", response_model=ResponsePostSchema)
async def create(
def create(
metric_schema: CreateSchema,
metric: MetricServiceInterface = Depends(metric_service),
_: dict[str] = Depends(UnionAuth(['pinger.metric.create'])),
):
"""Создание метрики."""
id_ = await metric.create(metric_schema.model_dump())
return ResponsePostSchema(**metric_schema.model_dump(), id=id_)
q = sa.insert(db_models.Metric).values(**metric_schema.model_dump()).returning(db_models.Metric)
metric = db.session.scalar(q)
db.session.flush()
return ResponsePostSchema(**metric_schema.model_dump(), id=metric.id_)


@router.get("")
async def get_all(
metric: MetricServiceInterface = Depends(metric_service),
def get_all(
_: dict[str] = Depends(UnionAuth(['pinger.metric.read'])),
):
"""Получение всех метрик."""
res = await metric.get_all()
return res
return list(db.session.scalars(sa.select(db_models.Metric)).all())


@router.get("/{id}")
async def get(
def get(
id: int,
metric: MetricServiceInterface = Depends(metric_service),
_: dict[str] = Depends(UnionAuth(['pinger.metric.read'])),
):
"""Получение одной метрики по id."""
try:
res = await metric.get_by_id(id)
q = sa.select(db_models.Metric).where(db_models.Metric.id_ == id)
res = db.session.scalar(q)
if not res:
raise exc.ObjectNotFound(id)
return res
except exc.ObjectNotFound:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return res
Loading
Loading