-
Notifications
You must be signed in to change notification settings - Fork 0
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
base: main
Are you sure you want to change the base?
Refractoring 1 #32
Changes from all commits
3e58ab4
696c963
8e13f8f
ca4b10c
b947ae9
5cb0ce0
ee1ed47
fa9c1ef
ea0b050
ed1a742
0c413fa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
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__) | ||
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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_) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А чего не из добавленного в БД, а из аргумента функции? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не очень ORM-way, он скорее предполагает что ты получаешь объект Fetcher ( |
||
.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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не понял нафига его было переносить, а особенно под routes. Пусть может в корне апишки лежит?