FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Pydantic V2 full support + massive refactoring by mahenzon · Pull Request #88 · mts-ai/FastAPI-JSONAPI · GitHub

Pydantic V2 full support + massive refactoring - #88

Closed
mahenzon wants to merge 94 commits into
dev-3.xfrom
feature/massive-upgrade
Closed

Pydantic V2 full support + massive refactoring#88
mahenzon wants to merge 94 commits into
dev-3.xfrom
feature/massive-upgrade

Conversation

mahenzon commented Jun 9, 2024
edited
Loading

Copy link
Copy Markdown
Member

TODO:

  • HTTPMethod переименовать и / или унифицировать
  • обновить примеры
  • обновить линтеры: ruff, black
  • избавиться от poetry, оставить только Hatch
  • mypy
  • orjson instead of simplejson
  • hatch env test (copy from ri-sdk)
  • older python versions support

return getattr(model_column, operator)(value)

raise InvalidFilters(detail=f"The field `{schema_field.title}` can't be null")
raise InvalidFilters(detail=f"The field `{field_name}` can't be null")

CosmoV Jun 17, 2024
edited
Loading

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

В сообщении об ошибке имя поля должно быть то же, что и в сваггере. Там может быть alias, это оно?


for type_to_cast in types:
try:
# Создаем экземпляр схемы для валидации значения

CosmoV Jun 17, 2024
edited
Loading

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Коммент соответствует действительности? Создание экземпляра схемы довольно дорогая операция, а в либе и так есть тормоза. Если нам нужно кастануть несериализованное значение в объект python надо найти другой способ это сделать


if SPLIT_REL in field:
value = {"field": SPLIT_REL.join(field.split(SPLIT_REL)[1:]), "order": self.sort_["order"]}
alias = aliased(self.related_model)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Поскольку планируем выпускать v3 версию либы есть некоторые мысли.

Я считаю, что использование рекурсивной логики и модели Node в данном репо антипаттерн. Если бы где-то строили AST и с ним работали еще имело бы смысл (не факт), а так код получается сложный, непонятный, и слабо расширяемый. Метод resolve становится точкой входа логику, которая будет бесконечно обрастать if условиями. Визуально может выглядеть привлекательно, но простота работы и производительность ниже чем конструирование фильтров через набор независимых функций.

В модуле fastapi_jsonapi/data_layers/filtering/sqlalchemy.py набор функций создан таким образом, чтобы они были максимально простыми и тестуруемыми.

Конкретно с алиасингом вида

alias = aliased(self.related_model)

уже натерпелись проблем когда создавались некорректные join конструкции.

Я предлагаю отказаться от этого класса и сделать следующее

  1. Определить интерфейсы для набора функций фильтрации и сортировки. Чтобы выглядели наподобие сингатуры build_filter_expressions
  2. Вынести эти интерфейсы в shared модули filtering/sorgting общие для различных DataLayer
  3. Вынести специфичные для sqla вещи в filterint/sorting модули в data_layers/sqlalchemy

На уровне DataLayer предлагаю делать вызовы как-то так. Псевдокод

from data_layers.shared.filteting import build_filter_expressions
from data_layers.shared.sorting import build_sort_expressions
from data_layers.sqla.filtering import specific_filter_handler
from data_layers.sqla.sorting import specific_sorting_getter

class SqlaDataLayer:
    async def build_filters(query_filter_conditions):
        return build_filter_expressions(
            dl_specific_callback=specific_filter_handler, 
            ... # other args
        )

    async def build_sorts(query_sort_conditions):
        return build_sorts_expressions(
            dl_specific_callback=specific_sorting_getter, 
            ... # other args
        )
        

Очень абстрактно без привязки к реальному коду, но думаю ты понял о чем я.

# don't allow arbitrary types, we don't know their behaviour
return TypeAdapter(field_type).validate_python
except PydanticSchemaGenerationError:
return field_type

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Я бы добавил сюда log.error

return None


def validate_relationship_name(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Я бы назвал check_relationship_exists поскольку проверка тут именно на существование

target_schema: type[TypeSchema],
target_model: type[TypeModel],
relationships_info: dict[RelationshipPath, RelationshipFilteringInfo],
) -> BinaryExpression:

CosmoV Jun 17, 2024
edited
Loading

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Над аннотацией return значения надо подумать. Возврат BinaryExpression специфично для sqla, по-хорошему было бы обобщить эту функцию превратив в публичный интерфейс и вынести её в разделяемый различными DataLayer модуль

mahenzon mentioned this pull request Jun 25, 2024

auvipy left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

wouldn't it be better to split the changes to make the changes merge more easily then changing everything at once?

Copy link
Copy Markdown
Member Author

wouldn't it be better to split the changes to make the changes merge more easily then changing everything at once?

Hi @auvipy
Thank you for your patience.
It's already so big it'll take too much time to split. I need a couple of free weekends to finish this up: update build config, update linters consigs, update docs, and that's it.
The code is already passing all the tests locally, so if you want to, you can check it by installing from the latest commit.

auvipy commented Aug 20, 2024

Copy link
Copy Markdown

Oh thats great

Copy link
Copy Markdown
Collaborator

Since these changes were included as part of the major changes in #97, this PR is closed. The update was applied not only to the Pydantic library but also included version upgrades for SQLAlchemy and FastAPI. Performance has more than doubled; for example, with 50 users, the average response time decreased from 302 ms to 138 ms. Thank you.

m-antonov closed this Mar 13, 2025
m-antonov deleted the feature/massive-upgrade branch March 13, 2025 10:58
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants


Back | FazBrowse Home | New Git URL