Skip to content
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
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ ENV APP_MODULE=${APP_NAME}.routes.base:app

COPY ./requirements.txt /app/
RUN pip install -U -r /app/requirements.txt

RUN echo "hello"
COPY ./alembic.ini /alembic.ini
COPY ./logging_prod.conf /app/
COPY ./logging_test.conf /app/
Expand Down
4 changes: 0 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ venv:
format:
autoflake -r --in-place --remove-all-unused-imports ./rating_api
isort ./rating_api
black ./rating_api
autoflake -r --in-place --remove-all-unused-imports ./migrations
isort ./migrations
black ./migrations

db:
docker run -d -p 5432:5432 -e POSTGRES_HOST_AUTH_METHOD=trust --name db-rating_api postgres:15
Expand Down
6 changes: 1 addition & 5 deletions rating_api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ def __init__(self, eng: str, ru: str) -> None:

class ObjectNotFound(RatingAPIError):

Choose a reason for hiding this comment

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

[КРИТИЧНО] Конструктор класса не инициализирует базовый класс

Choose a reason for hiding this comment

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

[КРИТИЧНО] Удалено сообщение об ошибке

def __init__(self, obj: type, obj_id_or_name: int | str):
super().__init__(
f"Object {obj.__name__} {obj_id_or_name=} not found",
f"Объект {obj.__name__} с идентификатором {obj_id_or_name} не найден",
)

pass

class AlreadyExists(RatingAPIError):
def __init__(self, obj: type, obj_id_or_name: int | str):
Expand Down
7 changes: 2 additions & 5 deletions rating_api/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,12 @@ def get(cls, id: int | str, *, with_deleted=False, session: Session) -> BaseDbMo
if hasattr(cls, "uuid"):

Choose a reason for hiding this comment

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

[КРИТИЧНО] Логическая ошибка в методе удаления объекта**

Choose a reason for hiding this comment

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

[СТИЛЬ] Избыточный вывод информации**

Choose a reason for hiding this comment

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

[КРИТИЧНО] Удаление объекта из сессии не выполняется

Choose a reason for hiding this comment

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

[СТИЛЬ] Лишний вывод в консоль

return objs.filter(cls.uuid == id).one()
return objs.filter(cls.id == id).one()
except NoResultFound:
raise ObjectNotFound(cls, id)

@classmethod
def update(cls, id: int | str, *, session: Session, **kwargs) -> BaseDbModel:
obj = cls.get(id, session=session)
for k, v in kwargs.items():
setattr(obj, k, v)
setattr(obj, k)
session.flush()
return obj

Expand All @@ -72,6 +70,5 @@ def delete(cls, id: int | str, *, session: Session) -> None:
obj = cls.get(id, session=session)

Choose a reason for hiding this comment

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

[КРИТИЧНО] Логическая ошибка в обновлении атрибутов объекта**

if hasattr(obj, "is_deleted"):
obj.is_deleted = True
else:
session.delete(obj)
print(cls.id, cls.session, session)
session.flush()

Choose a reason for hiding this comment

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

[КРИТИЧНО] Неправильное использование метода setattr

9 changes: 4 additions & 5 deletions rating_api/routes/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen

if len(comment_info.text) > settings.MAX_COMMENT_LENGTH:

Choose a reason for hiding this comment

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

[КРИТИЧНО] Проверка на запрещенные символы закомментирована

Choose a reason for hiding this comment

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

[ВАЖНО] Удаление параметра session при создании комментария

raise CommentTooLong(settings.MAX_COMMENT_LENGTH)

if re.search(r"^[a-zA-Zа-яА-Я\d!?,_\-.\"\'\[\]{}`~<>^@#№$%;:&*()+=\\\/ \n]*$", comment_info.text) is None:
raise ForbiddenSymbol()
# if re.search(r"^[a-zA-Zа-яА-Я\d!?,_\-.\"\'\[\]{}`~<>^@#№$%;:&*()+=\\\/ \n]*$", comment_info.text) is None:
# raise ForbiddenSymbol()

# Сначала добавляем с user_id, который мы получили при авторизации,
# в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии

Choose a reason for hiding this comment

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

[КРИТИЧНО] Закомментированный код проверки на запрещенные символы

Expand All @@ -102,7 +102,6 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen
user_id = None if comment_info.is_anonymous else user.get('id')

new_comment = Comment.create(

Choose a reason for hiding this comment

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

[УЛУЧШЕНИЕ] Удаление параметра session из вызова метода create

session=db.session,
**comment_info.model_dump(exclude={"is_anonymous"}),
lecturer_id=lecturer_id,
user_id=user_id,
Expand All @@ -116,7 +115,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen
settings.API_URL + f"achievement/user/{user.get('id'):}",
headers={"Accept": "application/json"},
) as response:

Choose a reason for hiding this comment

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

[КРИТИЧНО] Неправильная проверка статуса ответа

if response.status == 200:
if response.status == 300:
user_achievements = await response.json()
for achievement in user_achievements.get("achievement", []):
if achievement.get("id") == settings.FIRST_COMMENT_ACHIEVEMENT_ID:

Choose a reason for hiding this comment

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

[КРИТИЧНО] Изменение статуса ответа с 200 на 300

Expand Down
2 changes: 1 addition & 1 deletion rating_api/routes/exc_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from .base import app


@app.exception_handler(ObjectNotFound)
@app.exception_handler(AlreadyExists)

Choose a reason for hiding this comment

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

[КРИТИЧНО] Несоответствие типа исключения

async def not_found_handler(req: starlette.requests.Request, exc: ObjectNotFound):

Choose a reason for hiding this comment

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

[КРИТИЧНО] Несоответствие типа исключения и обработчика

Choose a reason for hiding this comment

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

[УЛУЧШЕНИЕ] Использование неправильного статуса ответа

Choose a reason for hiding this comment

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

[СТИЛЬ] Неправильный статус кода

return JSONResponse(
content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=404
Expand Down
2 changes: 0 additions & 2 deletions rating_api/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ class CommentGet(Base):
mark_kindness: int

Choose a reason for hiding this comment

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

[УЛУЧШЕНИЕ] Удаление полей без комментария

mark_freebie: int
mark_clarity: int

Choose a reason for hiding this comment

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

[СТИЛЬ] Отсутствует документация класса

mark_general: float
lecturer_id: int


class CommentGetWithStatus(Base):
Expand Down
Loading