-
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
Conversation
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.
Основное, что мне не нравится здесь
- Используется не ORM-way, когда взаимодействуешь с объектами. SQL-way (когда делаешь через select/update) нормальная тема, когда у тебя нет объектов или когда тебе нужны какие-то скаляры. Или когда сериализация в объекты занимает слишком значительное время. В остальных случаях в апишках лучше использовать подход через ORM объекты
- Стиль заметно отличается от других апишек
- Не вижу чтобы изменился воркер. Он не взаимодействовал с объектами из папки Service?
- Тесты не проходят
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. Пусть может в корне апишки лежит?
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() |
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.
А почему не как во всех апишках?
from db_models import Fetcher
fetcher = Fetcher(**create_schema.model_dump())
q = db.session.add(fetcher)
db.session.flush()
q = sa.insert(db_models.Fetcher).values(**create_schema.model_dump()).returning(db_models.Fetcher) | ||
fetcher = db.session.scalar(q) | ||
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 comment
The 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 comment
The reason will be displayed to describe this comment to others. Learn more.
Делается через from_attributes в конфиге ResponsePostSchema
_: 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 comment
The reason will be displayed to describe this comment to others. Learn more.
Какая сложная штука
+непонятно что вернет, где схема?
except exc.ObjectNotFound: | ||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) |
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.
Давай через Exception handler мб?
except exc.ObjectNotFound: | ||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) |
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.
Exception handler?
_: 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 comment
The reason will be displayed to describe this comment to others. Learn more.
А почему ты забираешь скаляр? Это id возвращает же? Одно значение, не объект. Тут бы хотелось видеть атрибуты фетчера
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 comment
The reason will be displayed to describe this comment to others. Learn more.
Не очень ORM-way, он скорее предполагает что ты получаешь объект Fetcher (db.session.get(Fetcher, id)
), редачишь его и после делаешь flush.
@@ -39,6 +49,7 @@ def test_post_success(crud_client): | |||
|
|||
@pytest.mark.authenticated("pinger.fetcher.read") | |||
def test_get_by_id_success(crud_client, this_fetcher): | |||
global fetcher |
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.
О_о
|
||
|
||
metric = {"name": "string", "ok": True, "time_delta": 0} | ||
|
||
|
||
@pytest_asyncio.fixture | ||
async def this_metric(dbsession): | ||
yield await PgMetricService(dbsession).create(item=metric) | ||
global metric |
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.
О_о
Изменения
Снес все классы сервисов
Убрал ручки alert (и вообще упоминание alert ото всюду)
Удалил асинки
Пофиксил тесты