From 600d52414e81c9b02f568c884981f13602179b51 Mon Sep 17 00:00:00 2001 From: Untone Date: Fri, 1 Nov 2024 10:04:32 +0300 Subject: [PATCH] txt --- CHANGELOG.md | 169 ++++++++++++++++++++++---------------------- docs/load_shouts.md | 2 +- resolvers/feed.py | 17 +++-- resolvers/reader.py | 32 ++++++++- 4 files changed, 125 insertions(+), 95 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03625997..82b2a32b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,59 +1,60 @@ -[0.4.6] +#### [0.4.6] +- `docs` added - optimized and unified `load_shouts_*` resolvers with `LoadShoutsOptions` - `load_shouts_bookmarked` resolver fixed -- `refactored with `resolvers/feed.py` +- refactored with `resolvers/feed` - model updates: - `ShoutsOrderBy` enum added - - `Shout.main_topic` from `ShoutTopic.main` type output + - `Shout.main_topic` from `ShoutTopic.main` as `Topic` type output - `Shout.created_by` as `Author` type output -[0.4.5] +#### [0.4.5] - `bookmark_shout` mutation resolver added -- load_bookmarked_shouts resolver fix -- community stats in orm +- `load_shouts_bookmarked` resolver added - `get_communities_by_author` resolver added -- `get_communities_all` resolver fix -- reaction filter by kinds +- `get_communities_all` resolver fixed +- `Community` stats in orm +- `Community` CUDL resolvers added +- `Reaction` filter by `Reaction.kind`s - `ReactionSort` enum added - `CommunityFollowerRole` enum added - `InviteStatus` enum added - `Topic.parents` ids added -- community CUDL resolvers added - `get_shout` resolver accepts slug or shout_id -[0.4.4] -- followers_stat removed for shout +#### [0.4.4] +- `followers_stat` removed for shout - sqlite3 support added - `rating_stat` and `commented_stat` fixes -[0.4.3] +#### [0.4.3] - cache reimplemented - load shouts queries unified -- followers_stat +- `followers_stat` removed from shout -[0.4.2] +#### [0.4.2] - reactions load resolvers separated for ratings (no stats) and comments - reactions stats improved -- load_comment_ratings separate resolver +- `load_comment_ratings` separate resolver -[0.4.1] +#### [0.4.1] - follow/unfollow logic updated and unified with cache -[0.4.0] +#### [0.4.0] - chore: version migrator synced - feat: precache_data on start - fix: store id list for following cache data - fix: shouts stat filter out deleted -[0.3.5] +#### [0.3.5] - cache isolated to services - topics followers and authors cached - redis stores lists of ids -[0.3.4] -- load_authors_by from cache +#### [0.3.4] +- `load_authors_by` from cache -[0.3.3] +#### [0.3.3] - feat: sentry integration enabled with glitchtip - fix: reindex on update shout - packages upgrade, isort @@ -61,143 +62,141 @@ - fix: feed featured filter - fts search removed -[0.3.2] +#### [0.3.2] - redis cache for what author follows - redis cache for followers - graphql add query: get topic followers -[0.3.1] +#### [0.3.1] - enabling sentry - long query log report added - editor fixes -- authors links cannot be updated by update_shout anymore +- authors links cannot be updated by `update_shout` anymore -[0.3.0] -- Shout.featured_at timestamp of the frontpage featuring event +#### [0.3.0] +- `Shout.featured_at` timestamp of the frontpage featuring event - added proposal accepting logics - schema modulized - Shout.visibility removed -[0.2.22] +#### [0.2.22] - added precommit hook - fmt - granian asgi -[0.2.21] +#### [0.2.21] - fix: rating logix -- fix: load_top_random_shouts -- resolvers: add_stat_* refactored +- fix: `load_top_random_shouts` +- resolvers: `add_stat_*` refactored - services: use google analytics - services: minor fixes search -[0.2.20] +#### [0.2.20] - services: ackee removed - services: following manager fixed - services: import views.json -[0.2.19] -- fix: adding 'author' role -- fix: stripping user_id in auth connector +#### [0.2.19] +- fix: adding `author` role +- fix: stripping `user_id` in auth connector -[0.2.18] -- schema: added Shout.seo string field -- resolvers: added /new-author webhook resolver +#### [0.2.18] +- schema: added `Shout.seo` string field +- resolvers: added `/new-author` webhook resolver - resolvers: added reader.load_shouts_top_random - resolvers: added reader.load_shouts_unrated -- resolvers: community follower id property name is .author -- resolvers: get_authors_all and load_authors_by +- resolvers: community follower id property name is `.author` +- resolvers: `get_authors_all` and `load_authors_by` - services: auth connector upgraded +#### [0.2.17] +- schema: enum types workaround, `ReactionKind`, `InviteStatus`, `ShoutVisibility` +- schema: `Shout.created_by`, `Shout.updated_by` +- schema: `Shout.authors` can be empty +- resolvers: optimized `reacted_shouts_updates` query -[0.2.17] -- schema: enum types workaround, ReactionKind, InviteStatus, ShoutVisibility -- schema: Shout.created_by, Shout.updated_by -- schema: Shout.authors can be empty -- resovlers: optimized reacted shouts updates query - - -[0.2.16] +#### [0.2.16] - resolvers: collab inviting logics - resolvers: queries and mutations revision and renaming -- resolvers: delete_topic(slug) implemented -- resolvers: added get_shout_followers -- resolvers: load_shouts_by filters implemented +- resolvers: `delete_topic(slug)` implemented +- resolvers: added `get_shout_followers` +- resolvers: `load_shouts_by` filters implemented - orm: invite entity -- schema: Reaction.range -> Reaction.quote -- filters: time_ago -> after +- schema: `Reaction.range` -> `Reaction.quote` +- filters: `time_ago` -> `after` - httpx -> aiohttp -[0.2.15] -- schema: Shout.created_by removed -- schema: Shout.mainTopic removed +#### [0.2.15] +- schema: `Shout.created_by` removed +- schema: `Shout.mainTopic` removed - services: cached elasticsearch connector -- services: auth is using user_id from authorizer -- resolvers: notify_* usage fixes -- resolvers: getAuthor now accepts slug, user_id or author_id +- services: auth is using `user_id` from authorizer +- resolvers: `notify_*` usage fixes +- resolvers: `getAuthor` now accepts slug, `user_id` or `author_id` - resolvers: login_required usage fixes -[0.2.14] +#### [0.2.14] - schema: some fixes from migrator -- schema: .days -> .time_ago -- schema: excludeLayout + layout in filters -> layouts +- schema: `.days` -> `.time_ago` +- schema: `excludeLayout` + `layout` in filters -> `layouts` - services: db access simpler, no contextmanager - services: removed Base.create() method - services: rediscache updated - resolvers: get_reacted_shouts_updates as followedReactions query -[0.2.13] +#### [0.2.13] - services: db context manager -- services: ViewedStorage fixes +- services: `ViewedStorage` fixes - services: views are not stored in core db anymore - schema: snake case in model fields names - schema: no DateTime scalar -- resolvers: get_my_feed comments filter reactions body.is_not('') -- resolvers: get_my_feed query fix -- resolvers: LoadReactionsBy.days -> LoadReactionsBy.time_ago -- resolvers: LoadShoutsBy.days -> LoadShoutsBy.time_ago +- resolvers: `get_my_feed` comments filter reactions body.is_not('') +- resolvers: `get_my_feed` query fix +- resolvers: `LoadReactionsBy.days` -> `LoadReactionsBy.time_ago` +- resolvers: `LoadShoutsBy.days` -> `LoadShoutsBy.time_ago` -[0.2.12] -- Author.userpic -> Author.pic -- CommunityFollower.role is string now -- Author.user is string now +#### [0.2.12] +- `Author.userpic` -> `Author.pic` +- `CommunityFollower.role` is string now +- `Author.user` is string now -[0.2.11] +#### [0.2.11] - redis interface updated -- viewed interface updated -- presence interface updated +- `viewed` interface updated +- `presence` interface updated - notify on create, update, delete for reaction and shout - notify on follow / unfollow author - use pyproject - devmode fixed -[0.2.10] +#### [0.2.10] - community resolvers connected -[0.2.9] +#### [0.2.9] - starlette is back, aiohttp removed - aioredis replaced with aredis -[0.2.8] +#### [0.2.8] - refactored -[0.2.7] -- loadFollowedReactions now with login_required +#### [0.2.7] +- `loadFollowedReactions` now with `login_required` - notifier service api draft -- added shout visibility kind in schema +- added `shout` visibility kind in schema - community isolated from author in orm -[0.2.6] +#### [0.2.6] - redis connection pool - auth context fixes - communities orm, resolvers, schema -[0.2.5] +#### [0.2.5] - restructured - all users have their profiles as authors in core -- gittask, inbox and auth logics removed -- settings moved to base and now smaller +- `gittask`, `inbox` and `auth` logics removed +- `settings` moved to base and now smaller - new outside auth schema -- removed gittask, auth, inbox, migration +- removed `gittask`, `auth`, `inbox`, `migration` diff --git a/docs/load_shouts.md b/docs/load_shouts.md index 07bfd272..4d026d32 100644 --- a/docs/load_shouts.md +++ b/docs/load_shouts.md @@ -20,4 +20,4 @@ Параметры аналогичны `load_shouts_by`, но применяются дополнительные фильтры: -- `reacted` - фильтрует публикации, по которым пользователь проголосовал, по умолчанию не применяется +- `reacted` - фильтр наличия реакции пользователя \ No newline at end of file diff --git a/resolvers/feed.py b/resolvers/feed.py index 209dea4a..0e43667a 100644 --- a/resolvers/feed.py +++ b/resolvers/feed.py @@ -15,6 +15,14 @@ from utils.logger import root_logger as logger def apply_options(q, options, author_id: int): + """ + Применяет опции фильтрации и сортировки к запросу для данного автора. + + :param q: Исходный запрос. + :param options: Опции фильтрации и сортировки. + :param author_id: Идентификатор автора. + :return: Запрос с примененными опциями. + """ filters = options.get("filters") if isinstance(filters, dict): q = apply_filters(q, filters) @@ -158,8 +166,7 @@ async def reacted_shouts_updates(info, follower_id: int, options) -> List[Shout] Обновляет публикации, на которые подписан автор, с учетом реакций. :param follower_id: Идентификатор подписчика. - :param limit: Колиество пукликаций для загрузки. - :param offset: Смещение для пагинации. + :param options: Опции фильтрации и сортировки. :return: Список публикаций. """ shouts: List[Shout] = [] @@ -200,8 +207,7 @@ async def load_shouts_followed(_, info, options) -> List[Shout]: Загружает публикации, на которые подписан пользователь. :param info: Информация о контексте GraphQL. - :param limit: Количество публикаций для загрузки. - :param offset: Смещение для пагинации. + :param options: Опции фильтрации и сортировки. :return: Список публикаций. """ user_id = info.context["user_id"] @@ -224,8 +230,7 @@ async def load_shouts_followed_by(_, info, slug: str, options) -> List[Shout]: :param info: Информация о контексте GraphQL. :param slug: Slug автора. - :param limit: Количество публикаций для загрузки. - :param offset: Смещение для пагинации. + :param options: Опции фильтрации и сортировки. :return: Список публикаций. """ with local_session() as session: diff --git a/resolvers/reader.py b/resolvers/reader.py index 92b4d5e7..4224ed51 100644 --- a/resolvers/reader.py +++ b/resolvers/reader.py @@ -16,7 +16,13 @@ from utils.logger import root_logger as logger def has_field(info, fieldname: str) -> bool: - """Проверяет, запрошено ли поле :fieldname: в GraphQL запросе""" + """ + Проверяет, запрошено ли поле :fieldname: в GraphQL запросе + + :param info: Информация о контексте GraphQL + :param fieldname: Имя запрашиваемого поля + :return: True, если поле запрошено, False в противном случае + """ field_node = info.field_nodes[0] for selection in field_node.selection_set.selections: if hasattr(selection, "name") and selection.name.value == fieldname: @@ -25,7 +31,11 @@ def has_field(info, fieldname: str) -> bool: def query_with_stat(): - # Оптимизированный подзапрос статистики + """ + добавляет подзапрос статистики + + :return: Запрос с подзапросом статистики. + """ stats_subquery = ( select( Reaction.shout.label("shout_id"), @@ -277,6 +287,13 @@ async def get_shout(_, info, slug="", shout_id=0): def apply_sorting(q, options): + """ + Применение сортировки к запросу. + + :param q: Исходный запрос. + :param options: Опции фильтрации и сортировки. + :return: Запрос с примененной сортировкой. + """ # Определение поля для сортировки order_str = options.get("order_by") @@ -298,6 +315,8 @@ async def load_shouts_by(_, info, options): """ Загрузка публикаций с фильтрацией, сортировкой и пагинацией. + :param _: Корневой объект запроса (не используется) + :param info: Информация о контексте GraphQL :param options: Опции фильтрации и сортировки. :return: Список публикаций, удовлетворяющих критериям. """ @@ -327,6 +346,8 @@ async def load_shouts_search(_, info, text, options): """ Поиск публикаций по тексту. + :param _: Корневой объект запроса (не используется) + :param info: Информация о контексте GraphQL :param text: Строка поиска. :param options: Опции фильтрации и сортировки. :return: Список публикаций, найденных по тексту. @@ -364,6 +385,11 @@ async def load_shouts_search(_, info, text, options): async def load_shouts_unrated(_, info, options): """ Загрузка публикаций с менее чем 3 реакциями типа LIKE/DISLIKE + + :param _: Корневой объект запроса (не используется) + :param info: Информация о контексте GraphQL + :param options: Опции фильтрации и сортировки. + :return: Список публикаций. """ rated_shouts = ( select(Reaction.shout) @@ -439,7 +465,7 @@ async def load_shouts_random_topic(_, info, options): Загрузка случайной темы и связанных с ней публикаций. :param info: Информация о контексте GraphQL. - :param limit: Максимальное количество публикаций. + :param options: Опции фильтрации и сортировки. :return: Тема и связанные публикации. """ [topic] = get_topics_random(None, None, 1)