From 7b030a93bab0db73415653e8f9e9d3129fa8afa2 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 7 Dec 2024 01:49:29 +0300 Subject: [PATCH 01/20] Recomment with has_create_scope --- rating_api/routes/comment.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 1962433..983aa62 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -35,18 +35,17 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - user_comments: list[LecturerUserComment] = ( - LecturerUserComment.query(session=db.session).filter(LecturerUserComment.user_id == user.get("id")).all() - ) - for user_comment in user_comments: - if datetime.datetime.utcnow() - user_comment.update_ts < datetime.timedelta( - minutes=settings.COMMENT_CREATE_FREQUENCY_IN_MINUTES - ): - raise TooManyCommentRequests( - dtime=user_comment.update_ts - + datetime.timedelta(minutes=settings.COMMENT_CREATE_FREQUENCY_IN_MINUTES) - - datetime.datetime.utcnow() - ) + # Все комментарии пользователя за текущий месяц + current_month_start = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) + user_comments = LecturerUserComment.query(session=db.session).filter( + LecturerUserComment.user_id == user.get("id"), + LecturerUserComment.update_ts >= current_month_start + ).all() + + # Сравниваем количество комментариев с лимитом + if len(user_comments) >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: + raise TooManyCommentRequests(dtime=current_month_start) + # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии From 8a3530d2621025c1a76384dce689875386221151 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 7 Dec 2024 02:25:30 +0300 Subject: [PATCH 02/20] added Count() and update_ts and create_ts --- rating_api/routes/comment.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 983aa62..67dca8e 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -37,20 +37,27 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen if not has_create_scope: # Все комментарии пользователя за текущий месяц current_month_start = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) - user_comments = LecturerUserComment.query(session=db.session).filter( + user_comments_count = LecturerUserComment.query(session=db.session).filter( LecturerUserComment.user_id == user.get("id"), LecturerUserComment.update_ts >= current_month_start - ).all() + ).count() # Сравниваем количество комментариев с лимитом - if len(user_comments) >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: + if user_comments_count >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: raise TooManyCommentRequests(dtime=current_month_start) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) - + # То, что было: LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) + create_ts = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) + LecturerUserComment.create( + session=db.session, + lecturer_id=lecturer_id, + user_id=user.get('id'), + create_ts=create_ts, # Добавляем create_ts + update_ts=create_ts # И update_ts + ) # Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД user_id = None if comment_info.is_anonymous else user.get('id') From 83fd42481cc7f087142ebb7a5e199374013f27d6 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 7 Dec 2024 02:49:53 +0300 Subject: [PATCH 03/20] =?UTF-8?q?=D0=91=D0=B5=D0=B7=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=20=D0=B8=20=D0=BF=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D0=B2=D0=B8=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B2=D1=80?= =?UTF-8?q?=D0=B5=D0=BC=D1=8F=20=D0=BE=D1=81=D1=82=D0=B0=D0=B2=D1=88=D0=B5?= =?UTF-8?q?=D0=B9=D1=81=D1=8F=20=D0=B7=D0=B0=D0=B4=D0=B5=D1=80=D0=B6=D0=BA?= =?UTF-8?q?=D0=B8=20(47)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rating_api/routes/comment.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 67dca8e..fe8222d 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -44,12 +44,12 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen # Сравниваем количество комментариев с лимитом if user_comments_count >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: - raise TooManyCommentRequests(dtime=current_month_start) + raise TooManyCommentRequests(dtime=current_month_start + datetime.timedelta(month=1) - datetime.datetime.utcnow()) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - # То, что было: LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) + create_ts = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) LecturerUserComment.create( session=db.session, From ba133598e7465e19587cd6eb4016e78405bda73b Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 7 Dec 2024 03:23:21 +0300 Subject: [PATCH 04/20] comment before Make format From 352292594df257b2a90ae377cb203eb707b7019f Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 7 Dec 2024 23:17:18 +0300 Subject: [PATCH 05/20] Format, Use current_month_start, remaining delay time --- rating_api/routes/comment.py | 32 ++++++++++++++++++-------------- rating_api/settings.py | 2 +- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index fe8222d..e6eacd6 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -35,28 +35,32 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - # Все комментарии пользователя за текущий месяц - current_month_start = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) - user_comments_count = LecturerUserComment.query(session=db.session).filter( - LecturerUserComment.user_id == user.get("id"), - LecturerUserComment.update_ts >= current_month_start - ).count() - - # Сравниваем количество комментариев с лимитом + # Все комментарии пользователя за текущий месяц + current_month_start = current_month_start + user_comments_count = ( + LecturerUserComment.query(session=db.session) + .filter(LecturerUserComment.user_id == user.get("id"), LecturerUserComment.update_ts >= current_month_start) + .count() + ) + + # Сравниваем количество комментариев с лимитом if user_comments_count >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: - raise TooManyCommentRequests(dtime=current_month_start + datetime.timedelta(month=1) - datetime.datetime.utcnow()) - + raise TooManyCommentRequests( + dtime=current_month_start + datetime.timedelta(month=1) - datetime.datetime.utcnow() + ) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - - create_ts = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) + + create_ts = datetime.datetime( + datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1 + ) LecturerUserComment.create( session=db.session, lecturer_id=lecturer_id, user_id=user.get('id'), - create_ts=create_ts, # Добавляем create_ts - update_ts=create_ts # И update_ts + create_ts=create_ts, + update_ts=create_ts, ) # Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД user_id = None if comment_info.is_anonymous else user.get('id') diff --git a/rating_api/settings.py b/rating_api/settings.py index ed09146..6ea7b93 100644 --- a/rating_api/settings.py +++ b/rating_api/settings.py @@ -10,7 +10,7 @@ class Settings(BaseSettings): DB_DSN: PostgresDsn = 'postgresql://postgres@localhost:5432/postgres' ROOT_PATH: str = '/' + os.getenv("APP_NAME", "") - COMMENT_CREATE_FREQUENCY_IN_MINUTES: int = 1 + COMMENT_CREATE_FREQUENCY_IN_MONTH: int = 1 CORS_ALLOW_ORIGINS: list[str] = ['*'] CORS_ALLOW_CREDENTIALS: bool = True CORS_ALLOW_METHODS: list[str] = ['*'] From d51874ca771bffc2c3dfe2ac6ca720f244388559 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 8 Dec 2024 20:14:27 +0300 Subject: [PATCH 06/20] current_month_start has been initialized. and create_ts = current_month_start --- rating_api/routes/comment.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index e6eacd6..46bb049 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -36,7 +36,11 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen if not has_create_scope: # Все комментарии пользователя за текущий месяц - current_month_start = current_month_start + current_month_start = datetime.datetime( + datetime.datetime.now(ts=datetime.timezone.utc).year, + datetime.datetime.now(ts=datetime.timezone.utc).month, + 1, + ) user_comments_count = ( LecturerUserComment.query(session=db.session) .filter(LecturerUserComment.user_id == user.get("id"), LecturerUserComment.update_ts >= current_month_start) @@ -52,9 +56,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - create_ts = datetime.datetime( - datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1 - ) + create_ts = current_month_start LecturerUserComment.create( session=db.session, lecturer_id=lecturer_id, From 49683ab376ea7c1f62872432a3c0f5e74b0c6e69 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Tue, 10 Dec 2024 21:24:11 +0300 Subject: [PATCH 07/20] Two comment checks have been added --- rating_api/routes/comment.py | 25 +++++++++++++++++++++---- rating_api/settings.py | 2 ++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 46bb049..9423c46 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -41,18 +41,35 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen datetime.datetime.now(ts=datetime.timezone.utc).month, 1, ) + # Все комментарии пользователя за последние COMMENT_CREATE_FREQUENCY_IN_MONTH (n) месяцев user_comments_count = ( LecturerUserComment.query(session=db.session) - .filter(LecturerUserComment.user_id == user.get("id"), LecturerUserComment.update_ts >= current_month_start) + .filter( + LecturerUserComment.user_id == user.get("id"), + LecturerUserComment.update_ts + >= current_month_start - datetime.timedelta(days=COMMENT_CREATE_FREQUENCY_IN_MONTH * 30) + - datetime.timedelta( + days=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH * 31 + ), + ) .count() ) - # Сравниваем количество комментариев с лимитом - if user_comments_count >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: + if ( + user_comments_count >= settings.COUNT_COMMENT_FREQUENCY + ): # Проверка на превышение лимита (m разрешенных комментариев (За COMMENT_CREATE_FREQUENCY_IN_MONTH месяцев)) raise TooManyCommentRequests( - dtime=current_month_start + datetime.timedelta(month=1) - datetime.datetime.utcnow() + dtime=current_month_start + datetime.timedelta(days=30) - datetime.datetime.utcnow() ) + # Проверка на максимальное количество комментариев одному лектору от пользователя + user_comments_to_lecturer_count = ( + LecturerUserComment.query(session=db.session) + .filter(LecturerUserComment.user_id == user.get("id"), LecturerUserComment.lecturer_id == lecturer_id) + .count() + ) + if user_comments_to_lecturer_count >= settings.MAX_COMMENTS_TO_LECTURER: + raise TooManyCommentsToLecturer(lecturer_id) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии diff --git a/rating_api/settings.py b/rating_api/settings.py index 6ea7b93..5598ff2 100644 --- a/rating_api/settings.py +++ b/rating_api/settings.py @@ -11,6 +11,8 @@ class Settings(BaseSettings): DB_DSN: PostgresDsn = 'postgresql://postgres@localhost:5432/postgres' ROOT_PATH: str = '/' + os.getenv("APP_NAME", "") COMMENT_CREATE_FREQUENCY_IN_MONTH: int = 1 + COUNT_COMMENT_FREQUENCY: int = 20 + MAX_COMMENTS_TO_LECTURER: int = 10 CORS_ALLOW_ORIGINS: list[str] = ['*'] CORS_ALLOW_CREDENTIALS: bool = True CORS_ALLOW_METHODS: list[str] = ['*'] From 2f677de0d74a97c097a2753e5e01191a1725ca62 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Wed, 11 Dec 2024 00:25:23 +0300 Subject: [PATCH 08/20] 2 methods for comments From dc40de066fad0969860b7890c5a26a0624fdf112 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Thu, 12 Dec 2024 03:24:01 +0300 Subject: [PATCH 09/20] adding parameters and conditions --- rating_api/routes/comment.py | 18 +++++++++++++++++- rating_api/settings.py | 2 ++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 9423c46..46d2550 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -47,7 +47,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen .filter( LecturerUserComment.user_id == user.get("id"), LecturerUserComment.update_ts - >= current_month_start - datetime.timedelta(days=COMMENT_CREATE_FREQUENCY_IN_MONTH * 30) + >= current_month_start - datetime.timedelta(days=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH * 30) - datetime.timedelta( days=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH * 31 ), @@ -61,6 +61,22 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise TooManyCommentRequests( dtime=current_month_start + datetime.timedelta(days=30) - datetime.datetime.utcnow() ) + # Oграничение комментариев одному лектору за период + now = datetime.datetime.now(ts=datetime.timezone.utc) + cutoff_date_lecturer = now - datetime.timedelta(days=30 * settings.MONTH_LECTURER_FREQUENCY) # L месяцев назад + + lecturer_comments_count = ( + LecturerUserComment.query(session=db.session) + .filter( + LecturerUserComment.user_id == user.get("id"), + LecturerUserComment.lecturer_id == lecturer_id, + LecturerUserComment.update_ts >= cutoff_date_lecturer, + ) + .count() + ) + + if lecturer_comments_count >= settings.COMMENT_LECTURER_FREQUENCY: + raise TooManyCommentsToLecturer(lecturer_id) # Проверка на максимальное количество комментариев одному лектору от пользователя user_comments_to_lecturer_count = ( diff --git a/rating_api/settings.py b/rating_api/settings.py index 5598ff2..d1f6dd2 100644 --- a/rating_api/settings.py +++ b/rating_api/settings.py @@ -13,6 +13,8 @@ class Settings(BaseSettings): COMMENT_CREATE_FREQUENCY_IN_MONTH: int = 1 COUNT_COMMENT_FREQUENCY: int = 20 MAX_COMMENTS_TO_LECTURER: int = 10 + MONTH_LECTURER_FREQUENCY: int = k + COMMENT_LECTURER_FREQUENCY: int = l CORS_ALLOW_ORIGINS: list[str] = ['*'] CORS_ALLOW_CREDENTIALS: bool = True CORS_ALLOW_METHODS: list[str] = ['*'] From ae6357dde651d228367f175455a7a9a383ebe01a Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Thu, 12 Dec 2024 22:49:03 +0300 Subject: [PATCH 10/20] 4 variables have been added and changes have been made --- rating_api/routes/comment.py | 45 +++++++++++------------------------- rating_api/settings.py | 9 ++++---- 2 files changed, 17 insertions(+), 37 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 46d2550..4ef4b76 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -17,6 +17,7 @@ comment = APIRouter(prefix="/comment", tags=["Comment"]) + @comment.post("", response_model=CommentGet) async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depends(UnionAuth())) -> CommentGet: """ @@ -26,6 +27,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"] """ + current_month_start = datetime.datetime(now.year, now.month, 1) # Начало текущего месяца lecturer = Lecturer.get(session=db.session, id=lecturer_id) if not lecturer: raise ObjectNotFound(Lecturer, lecturer_id) @@ -35,36 +37,24 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - # Все комментарии пользователя за текущий месяц - current_month_start = datetime.datetime( - datetime.datetime.now(ts=datetime.timezone.utc).year, - datetime.datetime.now(ts=datetime.timezone.utc).month, - 1, - ) - # Все комментарии пользователя за последние COMMENT_CREATE_FREQUENCY_IN_MONTH (n) месяцев + now = datetime.datetime.now(tz=datetime.timezone.utc) + + # Определяем дату, до которой учитываем комментарии для проверки общего лимита. + date_count = current_month_start - relativedelta(months=settings.COMMENT_FREQUENCY_IN_MONTH) + user_comments_count = ( LecturerUserComment.query(session=db.session) .filter( LecturerUserComment.user_id == user.get("id"), - LecturerUserComment.update_ts - >= current_month_start - datetime.timedelta(days=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH * 30) - - datetime.timedelta( - days=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH * 31 - ), + LecturerUserComment.update_ts >= date_count, ) .count() ) - if ( - user_comments_count >= settings.COUNT_COMMENT_FREQUENCY - ): # Проверка на превышение лимита (m разрешенных комментариев (За COMMENT_CREATE_FREQUENCY_IN_MONTH месяцев)) - raise TooManyCommentRequests( - dtime=current_month_start + datetime.timedelta(days=30) - datetime.datetime.utcnow() - ) - # Oграничение комментариев одному лектору за период - now = datetime.datetime.now(ts=datetime.timezone.utc) - cutoff_date_lecturer = now - datetime.timedelta(days=30 * settings.MONTH_LECTURER_FREQUENCY) # L месяцев назад - + if user_comments_count >= settings.COMMENT_LIMIT: + raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) + # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. + cutoff_date_lecturer = current_month_start - relativedelta(months=settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) lecturer_comments_count = ( LecturerUserComment.query(session=db.session) .filter( @@ -75,16 +65,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen .count() ) - if lecturer_comments_count >= settings.COMMENT_LECTURER_FREQUENCY: - raise TooManyCommentsToLecturer(lecturer_id) - - # Проверка на максимальное количество комментариев одному лектору от пользователя - user_comments_to_lecturer_count = ( - LecturerUserComment.query(session=db.session) - .filter(LecturerUserComment.user_id == user.get("id"), LecturerUserComment.lecturer_id == lecturer_id) - .count() - ) - if user_comments_to_lecturer_count >= settings.MAX_COMMENTS_TO_LECTURER: + if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: raise TooManyCommentsToLecturer(lecturer_id) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии diff --git a/rating_api/settings.py b/rating_api/settings.py index d1f6dd2..a465667 100644 --- a/rating_api/settings.py +++ b/rating_api/settings.py @@ -10,11 +10,10 @@ class Settings(BaseSettings): DB_DSN: PostgresDsn = 'postgresql://postgres@localhost:5432/postgres' ROOT_PATH: str = '/' + os.getenv("APP_NAME", "") - COMMENT_CREATE_FREQUENCY_IN_MONTH: int = 1 - COUNT_COMMENT_FREQUENCY: int = 20 - MAX_COMMENTS_TO_LECTURER: int = 10 - MONTH_LECTURER_FREQUENCY: int = k - COMMENT_LECTURER_FREQUENCY: int = l + COMMENT_FREQUENCY_IN_MONTH: int = 20 + COMMENT_LECTURER_FREQUENCE_IN_MONTH: int = 20 + COMMENT_LIMIT: int = 20 + COMMENT_TO_LECTURER_LIMIT: int = 20 CORS_ALLOW_ORIGINS: list[str] = ['*'] CORS_ALLOW_CREDENTIALS: bool = True CORS_ALLOW_METHODS: list[str] = ['*'] From da449cbb26514ba96d14d60966554166e6df7066 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 13 Dec 2024 00:08:35 +0300 Subject: [PATCH 11/20] 4 parametrs --- rating_api/routes/comment.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 4ef4b76..891298f 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -17,7 +17,6 @@ comment = APIRouter(prefix="/comment", tags=["Comment"]) - @comment.post("", response_model=CommentGet) async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depends(UnionAuth())) -> CommentGet: """ @@ -51,7 +50,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen .count() ) - if user_comments_count >= settings.COMMENT_LIMIT: + if user_comments_count >= settings.COMMENT_LIMIT: raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. cutoff_date_lecturer = current_month_start - relativedelta(months=settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) From 67d5ead83e57f878eb855de1b377b0b97b9a316f Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sat, 14 Dec 2024 01:53:05 +0300 Subject: [PATCH 12/20] Now initialized, constants defined, 2 variables introduced --- rating_api/exceptions.py | 13 +++++++++++++ rating_api/routes/comment.py | 13 +++++++++---- rating_api/settings.py | 6 +++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/rating_api/exceptions.py b/rating_api/exceptions.py index f575f96..f282eeb 100644 --- a/rating_api/exceptions.py +++ b/rating_api/exceptions.py @@ -39,6 +39,19 @@ def __init__(self, dtime: datetime.timedelta): ) +class TooManyCommentsToLecturer(RatingAPIError): + frequency: int + limit: int + + def __init__(self, frequency: int, limit: int): + self.frequency = frequency + self.limit = limit + super().__init__( + f"Too many comments to lecturer. Allowed: {limit} comments per {frequency} months.", + f"Превышен лимит комментариев лектору. Разрешено: {limit} комментариев за {frequency} месяцев.", + ) + + class ForbiddenAction(RatingAPIError): def __init__(self, type: Type): super().__init__(f"Forbidden action with {type.__name__}", f"Запрещенное действие с объектом {type.__name__}") diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 891298f..b1970a9 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -1,6 +1,10 @@ import datetime from typing import Literal from uuid import UUID +from dateutil.relativedelta import relativedelta + +# pip install python-dateutil + from auth_lib.fastapi import UnionAuth from fastapi import APIRouter, Depends, Query @@ -15,6 +19,7 @@ settings: Settings = get_settings() comment = APIRouter(prefix="/comment", tags=["Comment"]) +now = datetime.datetime.now(tz=datetime.timezone.utc) @comment.post("", response_model=CommentGet) @@ -36,10 +41,8 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - now = datetime.datetime.now(tz=datetime.timezone.utc) - - # Определяем дату, до которой учитываем комментарии для проверки общего лимита. date_count = current_month_start - relativedelta(months=settings.COMMENT_FREQUENCY_IN_MONTH) + # Определяем дату, до которой учитываем комментарии для проверки общего лимита. user_comments_count = ( LecturerUserComment.query(session=db.session) @@ -65,7 +68,9 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen ) if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: - raise TooManyCommentsToLecturer(lecturer_id) + raise TooManyCommentsToLecturer( + settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT + ) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии diff --git a/rating_api/settings.py b/rating_api/settings.py index a465667..1f7612c 100644 --- a/rating_api/settings.py +++ b/rating_api/settings.py @@ -10,10 +10,10 @@ class Settings(BaseSettings): DB_DSN: PostgresDsn = 'postgresql://postgres@localhost:5432/postgres' ROOT_PATH: str = '/' + os.getenv("APP_NAME", "") - COMMENT_FREQUENCY_IN_MONTH: int = 20 - COMMENT_LECTURER_FREQUENCE_IN_MONTH: int = 20 + COMMENT_FREQUENCY_IN_MONTH: int = 10 + COMMENT_LECTURER_FREQUENCE_IN_MONTH: int = 6 COMMENT_LIMIT: int = 20 - COMMENT_TO_LECTURER_LIMIT: int = 20 + COMMENT_TO_LECTURER_LIMIT: int = 5 CORS_ALLOW_ORIGINS: list[str] = ['*'] CORS_ALLOW_CREDENTIALS: bool = True CORS_ALLOW_METHODS: list[str] = ['*'] From 36806c08b6b94d7c91c82a74573bd3c023d714a8 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 09:53:33 +0300 Subject: [PATCH 13/20] comment --- rating_api/routes/comment.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index b1970a9..d090ae9 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -1,7 +1,6 @@ import datetime from typing import Literal from uuid import UUID -from dateutil.relativedelta import relativedelta # pip install python-dateutil @@ -19,7 +18,6 @@ settings: Settings = get_settings() comment = APIRouter(prefix="/comment", tags=["Comment"]) -now = datetime.datetime.now(tz=datetime.timezone.utc) @comment.post("", response_model=CommentGet) @@ -31,7 +29,6 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"] """ - current_month_start = datetime.datetime(now.year, now.month, 1) # Начало текущего месяца lecturer = Lecturer.get(session=db.session, id=lecturer_id) if not lecturer: raise ObjectNotFound(Lecturer, lecturer_id) @@ -41,7 +38,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - date_count = current_month_start - relativedelta(months=settings.COMMENT_FREQUENCY_IN_MONTH) + date_count = datetime.datetime(now.year - (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12, (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) % 12, 1) # Определяем дату, до которой учитываем комментарии для проверки общего лимита. user_comments_count = ( @@ -56,7 +53,8 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen if user_comments_count >= settings.COMMENT_LIMIT: raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. - cutoff_date_lecturer = current_month_start - relativedelta(months=settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) + + cutoff_date_lecturer = datetime.datetime(now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, 1) lecturer_comments_count = ( LecturerUserComment.query(session=db.session) .filter( @@ -65,16 +63,15 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen LecturerUserComment.update_ts >= cutoff_date_lecturer, ) .count() - ) - - if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: - raise TooManyCommentsToLecturer( - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT ) + + if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: + raise TooManyCommentsToLecturer(settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT) + # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - create_ts = current_month_start + create_ts = datetime.datetime(now.year, now.month, 1) LecturerUserComment.create( session=db.session, lecturer_id=lecturer_id, From 693c3ffe466e996b487a659ff8b005f94693598b Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 12:45:00 +0300 Subject: [PATCH 14/20] comment --- rating_api/routes/comment.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index d090ae9..259a98d 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -22,6 +22,7 @@ @comment.post("", response_model=CommentGet) async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depends(UnionAuth())) -> CommentGet: + now = datetime.datetime.now(tz=datetime.timezone.utc) """ Scopes: `["rating.comment.import"]` Создает комментарий к преподавателю в базе данных RatingAPI @@ -38,7 +39,11 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: - date_count = datetime.datetime(now.year - (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12, (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) % 12, 1) + date_count = datetime.datetime( + now.year - (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12, + (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) % 12, + 1, + ) # Определяем дату, до которой учитываем комментарии для проверки общего лимита. user_comments_count = ( @@ -50,11 +55,20 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen .count() ) + if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: + raise TooManyCommentsToLecturer( + settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT + ) + if user_comments_count >= settings.COMMENT_LIMIT: raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. - - cutoff_date_lecturer = datetime.datetime(now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, 1) + + cutoff_date_lecturer = datetime.datetime( + now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, + (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, + 1, + ) lecturer_comments_count = ( LecturerUserComment.query(session=db.session) .filter( @@ -63,11 +77,8 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen LecturerUserComment.update_ts >= cutoff_date_lecturer, ) .count() - ) + ) - if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: - raise TooManyCommentsToLecturer(settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT) - # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии From 3f5c18a6521158ff2dc88d28488e70436cc3b1e5 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 12:50:06 +0300 Subject: [PATCH 15/20] Comment 1 From e56c2e0cbbf2c24ce3e3d722871f7d634333bde5 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 19:02:53 +0300 Subject: [PATCH 16/20] Removed comment, rewritten error model for TooManyCommentRequests --- rating_api/routes/comment.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 259a98d..35adf55 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -2,14 +2,11 @@ from typing import Literal from uuid import UUID -# pip install python-dateutil - - from auth_lib.fastapi import UnionAuth from fastapi import APIRouter, Depends, Query from fastapi_sqlalchemy import db -from rating_api.exceptions import ForbiddenAction, ObjectNotFound, TooManyCommentRequests +from rating_api.exceptions import ForbiddenAction, ObjectNotFound, TooManyCommentRequests, TooManyCommentsToLecturer from rating_api.models import Comment, Lecturer, LecturerUserComment, ReviewStatus from rating_api.schemas.base import StatusResponseModel from rating_api.schemas.models import CommentGet, CommentGetAll, CommentPost From 4b14b57b6c1719904a861143014086549d66fa36 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 19:05:19 +0300 Subject: [PATCH 17/20] Removed comment, rewritten error model for TooManyCommentRequests From 574102cfb3a86acb51e59d0af1fbe8cb0ccb9ccb Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 21:08:22 +0300 Subject: [PATCH 18/20] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B8=D0=BD?= =?UTF-8?q?=D0=B8=D1=86=D0=B8=D0=B0=D0=BB=D0=B8=D0=B7=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BD=D0=BD=D1=8B=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rating_api/routes/comment.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 35adf55..097afb8 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -28,6 +28,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"] """ lecturer = Lecturer.get(session=db.session, id=lecturer_id) + if not lecturer: raise ObjectNotFound(Lecturer, lecturer_id) @@ -51,6 +52,20 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen ) .count() ) + cutoff_date_lecturer = datetime.datetime( + now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, + (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, + 1, + ) + lecturer_comments_count = ( + LecturerUserComment.query(session=db.session) + .filter( + LecturerUserComment.user_id == user.get("id"), + LecturerUserComment.lecturer_id == lecturer_id, + LecturerUserComment.update_ts >= cutoff_date_lecturer, + ) + .count() + ) if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: raise TooManyCommentsToLecturer( @@ -61,21 +76,6 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. - cutoff_date_lecturer = datetime.datetime( - now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, - 1, - ) - lecturer_comments_count = ( - LecturerUserComment.query(session=db.session) - .filter( - LecturerUserComment.user_id == user.get("id"), - LecturerUserComment.lecturer_id == lecturer_id, - LecturerUserComment.update_ts >= cutoff_date_lecturer, - ) - .count() - ) - # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии From 21fe934d0442a95bd9d6049cac439e71a956adc3 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Sun, 15 Dec 2024 21:36:05 +0300 Subject: [PATCH 19/20] fixed mistakes --- rating_api/exceptions.py | 12 +++++++----- rating_api/routes/exc_handlers.py | 9 ++++++++- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/rating_api/exceptions.py b/rating_api/exceptions.py index f282eeb..0777ad2 100644 --- a/rating_api/exceptions.py +++ b/rating_api/exceptions.py @@ -29,13 +29,15 @@ def __init__(self, obj: type, obj_id_or_name: int | str): class TooManyCommentRequests(RatingAPIError): - delay_time: datetime.timedelta + frequency: int + limit: int - def __init__(self, dtime: datetime.timedelta): - self.delay_time = dtime + def __init__(self, frequency: int, limit: int): + self.frequency = frequency + self.limit = limit super().__init__( - f'Too many comment requests. Delay: {dtime}', - f'Слишком много попыток оставить комментарий. Задержка: {dtime}', + f'Too many comment requests. Allowed: {limit} comments per {frequency} months.', + f'Слишком много попыток оставить комментарий. Разрешено: {limit} комментариев за {frequency} месяцев.', ) diff --git a/rating_api/routes/exc_handlers.py b/rating_api/routes/exc_handlers.py index 3dcb940..9f2ecc3 100644 --- a/rating_api/routes/exc_handlers.py +++ b/rating_api/routes/exc_handlers.py @@ -1,7 +1,7 @@ import starlette.requests from starlette.responses import JSONResponse -from rating_api.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound, TooManyCommentRequests, WrongMark +from rating_api.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound, TooManyCommentRequests,TooManyCommentsToLecturer, WrongMark from rating_api.schemas.base import StatusResponseModel from .base import app @@ -26,6 +26,13 @@ async def too_many_comment_handler(req: starlette.requests.Request, exc: Already return JSONResponse( content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=429 ) + +@app.exception_handler(TooManyCommentsToLecturer) +async def too_many_comment_handler(req: starlette.requests.Request, exc: AlreadyExists): + return JSONResponse( + content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=429 + ) + @app.exception_handler(ForbiddenAction) From 7dc047e17a2ef528471c9bbcc24fb870b137fa90 Mon Sep 17 00:00:00 2001 From: Timur Enikeev Date: Sun, 15 Dec 2024 18:15:15 -0500 Subject: [PATCH 20/20] minor adjustments --- rating_api/exceptions.py | 1 - rating_api/routes/comment.py | 19 ++++++++----------- rating_api/routes/exc_handlers.py | 13 ++++++++++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/rating_api/exceptions.py b/rating_api/exceptions.py index 0777ad2..c0b57d4 100644 --- a/rating_api/exceptions.py +++ b/rating_api/exceptions.py @@ -1,4 +1,3 @@ -import datetime from typing import Type diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 097afb8..e931696 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -19,7 +19,6 @@ @comment.post("", response_model=CommentGet) async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depends(UnionAuth())) -> CommentGet: - now = datetime.datetime.now(tz=datetime.timezone.utc) """ Scopes: `["rating.comment.import"]` Создает комментарий к преподавателю в базе данных RatingAPI @@ -28,6 +27,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"] """ lecturer = Lecturer.get(session=db.session, id=lecturer_id) + now = datetime.datetime.now(tz=datetime.timezone.utc) if not lecturer: raise ObjectNotFound(Lecturer, lecturer_id) @@ -37,13 +37,12 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen raise ForbiddenAction(Comment) if not has_create_scope: + # Определяем дату, до которой учитываем комментарии для проверки общего лимита. date_count = datetime.datetime( - now.year - (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12, + now.year + (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) // 12, (now.month - settings.COMMENT_FREQUENCY_IN_MONTH) % 12, 1, ) - # Определяем дату, до которой учитываем комментарии для проверки общего лимита. - user_comments_count = ( LecturerUserComment.query(session=db.session) .filter( @@ -52,8 +51,12 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen ) .count() ) + if user_comments_count >= settings.COMMENT_LIMIT: + raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) + + # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. cutoff_date_lecturer = datetime.datetime( - now.year - (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, + now.year + (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) // 12, (now.month - settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH) % 12, 1, ) @@ -66,19 +69,13 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen ) .count() ) - if lecturer_comments_count >= settings.COMMENT_TO_LECTURER_LIMIT: raise TooManyCommentsToLecturer( settings.COMMENT_LECTURER_FREQUENCE_IN_MONTH, settings.COMMENT_TO_LECTURER_LIMIT ) - if user_comments_count >= settings.COMMENT_LIMIT: - raise TooManyCommentRequests(settings.COMMENT_FREQUENCY_IN_MONTH, settings.COMMENT_LIMIT) - # Дата, до которой учитываем комментарии для проверки лимита на комментарии конкретному лектору. - # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - create_ts = datetime.datetime(now.year, now.month, 1) LecturerUserComment.create( session=db.session, diff --git a/rating_api/routes/exc_handlers.py b/rating_api/routes/exc_handlers.py index 9f2ecc3..a0f0d4b 100644 --- a/rating_api/routes/exc_handlers.py +++ b/rating_api/routes/exc_handlers.py @@ -1,7 +1,14 @@ import starlette.requests from starlette.responses import JSONResponse -from rating_api.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound, TooManyCommentRequests,TooManyCommentsToLecturer, WrongMark +from rating_api.exceptions import ( + AlreadyExists, + ForbiddenAction, + ObjectNotFound, + TooManyCommentRequests, + TooManyCommentsToLecturer, + WrongMark, +) from rating_api.schemas.base import StatusResponseModel from .base import app @@ -26,7 +33,8 @@ async def too_many_comment_handler(req: starlette.requests.Request, exc: Already return JSONResponse( content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=429 ) - + + @app.exception_handler(TooManyCommentsToLecturer) async def too_many_comment_handler(req: starlette.requests.Request, exc: AlreadyExists): return JSONResponse( @@ -34,7 +42,6 @@ async def too_many_comment_handler(req: starlette.requests.Request, exc: Already ) - @app.exception_handler(ForbiddenAction) async def forbidden_action_handler(req: starlette.requests.Request, exc: AlreadyExists): return JSONResponse(