-
-
Notifications
You must be signed in to change notification settings - Fork 38
Исправление ошибки в логах при импорте #261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
Руководство для проверяющегоЭтот PR исправляет ошибки импорта и логирования, динамически загружая номер версии в setup.py, чтобы избежать циклических зависимостей, повышает версию пакета до 1.8.6 и обновляет отладочные сообщения журнала для использования f-строк для правильного форматирования JSON. Блок-схема получения версии в setup.pyflowchart TD
A[setup.py] --> B[Open fast_bitrix24/__version__.py]
B --> C[exec file contents to get __version__]
C --> D[Use __version__ in setup configuration]
Изменения на уровне файлов
Советы и командыВзаимодействие с Sourcery
Настройка вашего опытаПерейдите в свою панель управления, чтобы:
Получение помощи
Original review guide in EnglishReviewer's GuideThis PR addresses import and logging errors by loading the version number dynamically in setup.py to avoid circular dependencies, bumps the package version to 1.8.6, and updates debug logging statements to use f-strings for correct JSON formatting. Flow diagram for version retrieval in setup.pyflowchart TD
A[setup.py] --> B[Open fast_bitrix24/__version__.py]
B --> C[exec file contents to get __version__]
C --> D[Use __version__ in setup configuration]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Привет, @GeorgeNikitinNV - я проверил ваши изменения, и они выглядят отлично!
Подсказка для AI Agents
Пожалуйста, обратите внимание на комментарии из этого обзора кода:
## Индивидуальные комментарии
### Комментарий 1
<location> `fast_bitrix24/srh.py:194` </location>
<code_context>
json = await response.json(encoding="utf-8")
- logger.debug("Response: %s", json)
+ logger.debug(f"Response: {str(json)}")
self.add_throttler_records(method, params, json)
</code_context>
<issue_to_address>
Использование f-строки с str(json) может не предоставить столько полезной информации, как логирование объекта напрямую.
Передача объекта напрямую в logger.debug сохраняет форматирование и может улучшить читаемость, особенно для сложных объектов. Рассмотрите возможность возврата к logger.debug("Response: %s", json).
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
logger.debug(f"Response: {str(json)}")
=======
logger.debug("Response: %s", json)
>>>>>>> REPLACE
</suggested_fix>
Sourcery бесплатен для открытого исходного кода - если вам нравятся наши обзоры, пожалуйста, поделитесь ими ✨
Original comment in English
Hey @GeorgeNikitinNV - I've reviewed your changes and they look great!
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location> `fast_bitrix24/srh.py:194` </location>
<code_context>
json = await response.json(encoding="utf-8")
- logger.debug("Response: %s", json)
+ logger.debug(f"Response: {str(json)}")
self.add_throttler_records(method, params, json)
</code_context>
<issue_to_address>
Using f-string with str(json) may not provide as much useful information as logging the object directly.
Passing the object directly to logger.debug preserves formatting and can improve readability, especially for complex objects. Consider reverting to logger.debug("Response: %s", json).
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
logger.debug(f"Response: {str(json)}")
=======
logger.debug("Response: %s", json)
>>>>>>> REPLACE
</suggested_fix>
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
@@ -191,7 +191,7 @@ async def request_attempt(self, method, params=None) -> dict: | |||
) as response: | |||
json = await response.json(encoding="utf-8") | |||
|
|||
logger.debug("Response: %s", json) | |||
logger.debug(f"Response: {str(json)}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
предложение: Использование f-строки с str(json) может не предоставить столько полезной информации, как логирование объекта напрямую.
Передача объекта напрямую в logger.debug сохраняет форматирование и может улучшить читаемость, особенно для сложных объектов. Рассмотрите возможность возврата к logger.debug("Response: %s", json).
logger.debug(f"Response: {str(json)}") | |
logger.debug("Response: %s", json) |
Original comment in English
suggestion: Using f-string with str(json) may not provide as much useful information as logging the object directly.
Passing the object directly to logger.debug preserves formatting and can improve readability, especially for complex objects. Consider reverting to logger.debug("Response: %s", json).
logger.debug(f"Response: {str(json)}") | |
logger.debug("Response: %s", json) |
А вас не затруднит показать ошибки, которые выдает uv? А также множественные ошибки в логах. |
Да, не проблема - вот такие валятся при каждом вызове, после фикса их нет:
|
Сейчас откатился на Вашу версию (1.8.5), но пока воспроизвести глюк с |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Так, ну давайте тогда с uv отложим историю, а по логированию -- что там такого у вас в json?
Я не могу повторить ошибку.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Второй вопрос -- вы при инициализации Bitrix24 прописываете параметр client? Можете показать код инициализации?
|
json как json - вот пример:
|
О, удалось повторить ошибку после отката импорта. Когда я импортирую
[project]
...
dependencies = [
"fast-bitrix24>=0.4.0",
...
[tool.uv.sources]
fast-bitrix24 = { git = "https://github.com/<MY_FORK>/fast_bitrix24.git", rev = "Fix-logging" } то при ❯ uv sync
Updated https://github.com/<MY_FORK>/fast_bitrix24.git (71dff2ab1623293fc8ef259e83f3144e920a080c)
× Failed to build `fast-bitrix24 @ git+https://github.com/<MY_FORK>/fast_bitrix24.git@Fix-logging`
├─▶ The build backend returned an error
╰─▶ Call to `setuptools.build_meta:__legacy__.build_wheel` failed (exit status: 1)
[stderr]
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/Users/george.nikitin/.cache/uv/builds-v0/.tmpY39W1u/lib/python3.12/site-packages/setuptools/build_meta.py", line 331, in get_requires_for_build_wheel
return self._get_build_requires(config_settings, requirements=[])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/george.nikitin/.cache/uv/builds-v0/.tmpY39W1u/lib/python3.12/site-packages/setuptools/build_meta.py", line 301, in _get_build_requires
self.run_setup()
File "/Users/george.nikitin/.cache/uv/builds-v0/.tmpY39W1u/lib/python3.12/site-packages/setuptools/build_meta.py", line 512, in run_setup
super().run_setup(setup_script=setup_script)
File "/Users/george.nikitin/.cache/uv/builds-v0/.tmpY39W1u/lib/python3.12/site-packages/setuptools/build_meta.py", line 317, in run_setup
exec(code, locals())
File "<string>", line 2, in <module>
File "/Users/george.nikitin/.cache/uv/git-v0/checkouts/2b00622910832253/71dff2a/fast_bitrix24/__init__.py", line 3, in <module>
from fast_bitrix24.bitrix import Bitrix, BitrixAsync
File "/Users/george.nikitin/.cache/uv/git-v0/checkouts/2b00622910832253/71dff2a/fast_bitrix24/bitrix.py", line 9, in <module>
import aiohttp
ModuleNotFoundError: No module named 'aiohttp'
hint: This usually indicates a problem with the package or the build environment. Интересно, что при импорте из Вашего репо все работает, как надо (ну, кроме ошибок в логах, см. выше). Может быть, я что-то тут упускаю? |
Все равно не могу повторить ошибку с логированием. Запускаю такой скрипт from logging import getLogger
import json
logger = getLogger(__name__)
json_data = json.loads("""{
"result": {
"items": [
{
"id": 93,
"createdTime": "2025-05-31T02:10:40+03:00",
"updatedTime": "2025-05-31T02:10:40+03:00",
"createdBy": 27,
"updatedBy": 27,
"assignedById": 27,
"opened": "Y",
"title": "REDACTED",
"logo": "",
"address": null,
"addressLegal": null,
"bankingDetails": null,
"comments": null,
"typeId": "CUSTOMER",
"industry": "IT",
"revenue": 0,
"currencyId": "RUB",
"employees": "EMPLOYEES_1",
"leadId": null,
"webformId": 0,
"originatorId": null,
"originId": null,
"originVersion": null,
"hasPhone": "N",
"hasEmail": "N",
"hasImol": "N",
"isMyCompany": "N",
"searchContent": "REDACTED",
"categoryId": 0,
"lastActivityBy": 27,
"lastActivityTime": "2025-05-31T02:10:40+03:00",
"emailHome": "",
"emailWork": "",
"emailMailing": "",
"phoneMobile": "",
"phoneWork": "",
"phoneMailing": "",
"imol": "",
"email": "",
"phone": "",
"lastCommunicationTime": null,
"lastCommunicationCallTime": null,
"lastCommunicationEmailTime": null,
"lastCommunicationImolTime": null,
"lastCommunicationWebformTime": null,
"parentId1056": null,
"utmSource": null,
"utmMedium": null,
"utmCampaign": null,
"utmContent": null,
"utmTerm": null,
"observers": [],
"contactIds": [
123,
"REDACTED"
],
"entityTypeId": 4,
"UF_CRM_1750292035721": null,
"fm": []
}
],
"total": 45,
"time": {
"start": 1750395562.854183,
"finish": 1750395563.09679,
"duration": 0.24260711669921875,
"processing": 0.21869206428527832,
"date_start": "2025-06-20T07:59:22+03:00",
"date_finish": "2025-06-20T07:59:23+03:00",
"operating_reset_at": 1750396162,
"operating": 1.4807531833648682
}}}""")
logger.warning("Response: %s",json_data) Все отрабатывает без ошибок:
|
У меня зреет подозрение, что у вас какая-то нестрандартная среда. Какие-то либы подменены, возможно. Вы пробовали ставить либу в чистый venv? |
Вы можете написать минимальный тест, который будет использовать текущий код либы и демонстрировать ошибку? Сейчас речь пока только о логировании. |
042abe3
to
8314e53
Compare
При импорте библиотеки в логах возникают множественные ошибки.
Кроме того, версия не всегда корректно импортируется при установке с помощью
uv
, поскольку получается кольцевая зависимость - мы не можем получить версию вsetup.py
, пока не установим все пакеты, а установить не можем, поскольку версии нет. Предложен хак для исправления.Обзор от Sourcery
Исправлены ошибки импорта и логирования путем изменения получения версии в setup и исправления форматирования отладки.
Исправления ошибок:
Сборка:
__version__.py
вsetup.py
, чтобы избежать циклической зависимости при установкеМелкие задачи:
Original summary in English
Обзор от Sourcery
Исправлены ошибки импорта и ведения журнала во время установки и выполнения, путем загрузки файла версии в setup, чтобы избежать циклических зависимостей, увеличена версия пакета и переключены вызовы logger.debug на f-strings, чтобы предотвратить проблемы с форматированием JSON.
Исправления ошибок:
Сборка:
__version__.py
вsetup.py
для разрыва циклической зависимости при установкеПрочие работы:
Original summary in English
Summary by Sourcery
Fix import and logging errors during install and runtime by loading the version file in setup to avoid circular dependencies, bump the package version, and switch logger.debug calls to f-strings to prevent JSON formatting issues
Bug Fixes:
Build:
Chores: