From 7b277d02f3f332121d896df3c46c7020462bce37 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 29 Nov 2024 08:37:34 +0300 Subject: [PATCH 1/6] this comment --- rating_api/routes/comment.py | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 1962433..53d2c92 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -30,24 +30,22 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen if not lecturer: raise ObjectNotFound(Lecturer, lecturer_id) - has_create_scope = "rating.comment.import" in [scope['name'] for scope in user.get('session_scopes')] - if (comment_info.create_ts or comment_info.update_ts) and not has_create_scope: - 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() - ) - + 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.now().month - user_comment.update_ts < datetime.timedelta( + month=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH + ) and datetime.datetime.now().year != datetime.timedelta( + year=settings.COMMENT_CREATE_FREQUENCY_IN_YEAR + ): + raise TooManyCommentRequests( + dtime=user_comment.update_ts + + datetime.timedelta(month=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH) + + datetime.timedelta(year=settings.COMMENT_CREATE_FREQUENCY_IN_YEAR) + - datetime.datetime.now().month + - datetime.datetime.now().year + ) # Сначала добавляем с user_id, который мы получили при авторизации, # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) From cc2ac0fdda39d6c46a1457be393e079bcf086003 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 6 Dec 2024 09:00:40 +0300 Subject: [PATCH 2/6] Remake comment From 95a6ba879fdf85fb5a6195f1e8b21950e8447cff Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 6 Dec 2024 09:03:02 +0300 Subject: [PATCH 3/6] remake comment --- rating_api/routes/comment.py | 68 ++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 53d2c92..fd69296 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -26,41 +26,41 @@ 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) + +import datetime - 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.now().month - user_comment.update_ts < datetime.timedelta( - month=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH - ) and datetime.datetime.now().year != datetime.timedelta( - year=settings.COMMENT_CREATE_FREQUENCY_IN_YEAR - ): - raise TooManyCommentRequests( - dtime=user_comment.update_ts - + datetime.timedelta(month=settings.COMMENT_CREATE_FREQUENCY_IN_MONTH) - + datetime.timedelta(year=settings.COMMENT_CREATE_FREQUENCY_IN_YEAR) - - datetime.datetime.now().month - - datetime.datetime.now().year - ) - # Сначала добавляем с user_id, который мы получили при авторизации, - # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии - LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) - - # Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД - user_id = None if comment_info.is_anonymous else user.get('id') - - new_comment = Comment.create( - session=db.session, - **comment_info.model_dump(exclude={"is_anonymous"}), - lecturer_id=lecturer_id, - user_id=user_id, - review_status=ReviewStatus.PENDING, - ) - return CommentGet.model_validate(new_comment) +lecturer = Lecturer.get(session=db.session, id=lecturer_id) +if not lecturer: + raise ObjectNotFound(Lecturer, lecturer_id) + +current_month_start = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, 1) + +last_comment = LecturerUserComment.query.filter( + LecturerUserComment.lecturer_id == lecturer_id, + LecturerUserComment.user_id == user.get('id'), + LecturerUserComment.update_ts >= current_month_start +).order_by(LecturerUserComment.update_ts.desc()).first() + +if last_comment: + time_since_last_comment = datetime.datetime.now() - last_comment.update_ts + allowed_time = datetime.timedelta(days=30 * settings.COMMENT_CREATE_FREQUENCY_IN_MONTH) + if time_since_last_comment < allowed_time: + raise TooManyCommentRequests(dtime=last_comment.update_ts + allowed_time) + +# анонимность комментария +user_id = None if comment_info.is_anonymous else user.get('id') + +# Создаем комментарий только один раз +new_comment = LecturerUserComment.create( + session=db.session, + *comment_info.model_dump(exclude={"is_anonymous"}), + lecturer_id=lecturer_id, + user_id=user_id, + update_ts=datetime.datetime.now(), # обязательно установить update_ts + review_status=ReviewStatus.PENDING, +) + +return CommentGet.model_validate(new_comment) @comment.get("/{uuid}", response_model=CommentGet) From 73cf4c6045002ea5d77ef16e9a23c8a9844441f3 Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 6 Dec 2024 09:06:38 +0300 Subject: [PATCH 4/6] comment 2 --- rating_api/routes/comment.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index fd69296..dba0aff 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -56,7 +56,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen *comment_info.model_dump(exclude={"is_anonymous"}), lecturer_id=lecturer_id, user_id=user_id, - update_ts=datetime.datetime.now(), # обязательно установить update_ts + update_ts=datetime.datetime.now(), review_status=ReviewStatus.PENDING, ) From 288d12b6f1fe56debef5bad70875f4d8d1e2805a Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 6 Dec 2024 09:08:36 +0300 Subject: [PATCH 5/6] remake comment --- 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 dba0aff..2b457b5 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -26,8 +26,7 @@ async def create_comment(lecturer_id: int, comment_info: CommentPost, user=Depen Для возможности создания комментария с указанием времени создания и изменения необходим скоуп ["rating.comment.import"] """ - -import datetime + lecturer = Lecturer.get(session=db.session, id=lecturer_id) if not lecturer: From 8bc4461ee3b3d70626531a2238c872bda56bbb3a Mon Sep 17 00:00:00 2001 From: ValeryEstal Date: Fri, 6 Dec 2024 22:14:04 +0300 Subject: [PATCH 6/6] comment with has_create_scope --- rating_api/routes/comment.py | 106 ++++++++++++++++++++++++----------- 1 file changed, 72 insertions(+), 34 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 2b457b5..2213c9f 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -25,41 +25,79 @@ 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) - -current_month_start = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month, 1) - -last_comment = LecturerUserComment.query.filter( - LecturerUserComment.lecturer_id == lecturer_id, - LecturerUserComment.user_id == user.get('id'), - LecturerUserComment.update_ts >= current_month_start -).order_by(LecturerUserComment.update_ts.desc()).first() - -if last_comment: - time_since_last_comment = datetime.datetime.now() - last_comment.update_ts - allowed_time = datetime.timedelta(days=30 * settings.COMMENT_CREATE_FREQUENCY_IN_MONTH) - if time_since_last_comment < allowed_time: - raise TooManyCommentRequests(dtime=last_comment.update_ts + allowed_time) - -# анонимность комментария -user_id = None if comment_info.is_anonymous else user.get('id') - -# Создаем комментарий только один раз -new_comment = LecturerUserComment.create( - session=db.session, - *comment_info.model_dump(exclude={"is_anonymous"}), - lecturer_id=lecturer_id, - user_id=user_id, - update_ts=datetime.datetime.now(), - review_status=ReviewStatus.PENDING, -) + """ + + # Функция для форматирования даты в формат "Месяц Год" + def format_date(date_obj): + if isinstance(date_obj, datetime.datetime): + return date_obj.strftime("%B %Y") + return date_obj #Если это не datetime объект, возвращаем как есть + + lecturer = Lecturer.get(session=db.session, id=lecturer_id) + if not lecturer: + raise ObjectNotFound(Lecturer, lecturer_id) + + has_create_scope = "rating.comment.import" in [scope['name'] for scope in user.get('session_scopes')] + if (comment_info.create_ts or comment_info.update_ts) and not has_create_scope: + 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() + ) + + current_month_start = datetime.datetime(datetime.datetime.now(ts=datetime.timezone.utc).year, datetime.datetime.now(ts=datetime.timezone.utc).month, 1) + formatted_current_month_start = format_date(current_month_start) #Форматируем дату + + # Получаем все комментарии пользователя за текущий месяц. + user_comments_this_month = LecturerUserComment.query.filter( + LecturerUserComment.lecturer_id == lecturer_id, + LecturerUserComment.user_id == user.get('id'), + LecturerUserComment.update_ts <= current_month_start + ).all() + + #Проверка на превышение лимита комментариев + if len(user_comments_this_month) >= settings.COMMENT_CREATE_FREQUENCY_IN_MONTH: + raise TooManyCommentRequests(dtime=formatted_current_month_start) #Передаем отформатированную дату + + # Создаем новый комментарий + new_comment = LecturerUserComment.create( + session=db.session, + lecturer_id=lecturer_id, + user_id=user.get('id'), + update_ts=datetime.datetime.now() + ) -return CommentGet.model_validate(new_comment) + # Форматируем дату нового комментария + formatted_new_comment_date = format_date(new_comment.update_ts) + + last_comment = LecturerUserComment.query.filter( + LecturerUserComment.lecturer_id == lecturer_id, + LecturerUserComment.user_id == user.get('id'), + LecturerUserComment.update_ts >= current_month_start + ).order_by(LecturerUserComment.update_ts.desc()).first() + + if last_comment: + time_since_last_comment = datetime.datetime.now() - last_comment.update_ts + allowed_time = datetime.timedelta(days=30 * settings.COMMENT_CREATE_FREQUENCY_IN_MONTH) + if time_since_last_comment < allowed_time: + raise TooManyCommentRequests(dtime=last_comment.update_ts + allowed_time) + # Сначала добавляем с user_id, который мы получили при авторизации, + # в LecturerUserComment, чтобы нельзя было слишком быстро добавлять комментарии + LecturerUserComment.create(session=db.session, lecturer_id=lecturer_id, user_id=user.get('id')) + + # Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД + user_id = None if comment_info.is_anonymous else user.get('id') + + new_comment = Comment.create( + session=db.session, + **comment_info.model_dump(exclude={"is_anonymous"}), + lecturer_id=lecturer_id, + user_id=user_id, + review_status=ReviewStatus.PENDING,\ + ) + + return CommentGet.model_validate(new_comment) @comment.get("/{uuid}", response_model=CommentGet)