arpakitlib 3.0.2__tar.gz → 3.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/PKG-INFO +12 -15
  2. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/README.md +11 -14
  3. arpakitlib-3.0.4/arpakitlib/aiogram_/aiogram_as_tg_command_util.py +279 -0
  4. arpakitlib-3.0.2/arpakitlib/http_client_/ar_base_http_api_client_util.py → arpakitlib-3.0.4/arpakitlib/common_/base_http_api_client_util.py +3 -2
  5. arpakitlib-3.0.2/arpakitlib/common_/ar_base_worker_util.py → arpakitlib-3.0.4/arpakitlib/common_/base_worker_util.py +3 -3
  6. arpakitlib-3.0.2/arpakitlib/common_/ar_blank_util.py → arpakitlib-3.0.4/arpakitlib/common_/blank_util.py +1 -1
  7. arpakitlib-3.0.2/arpakitlib/common_/ar_cache_file_util.py → arpakitlib-3.0.4/arpakitlib/common_/cache_file_util.py +4 -3
  8. arpakitlib-3.0.2/arpakitlib/common_/ar_dict_as_object_util.py → arpakitlib-3.0.4/arpakitlib/common_/dict_as_object_util.py +1 -1
  9. arpakitlib-3.0.2/arpakitlib/common_/ar_file_storage_in_dir_util.py → arpakitlib-3.0.4/arpakitlib/common_/file_storage_in_dir_util.py +2 -2
  10. arpakitlib-3.0.2/arpakitlib/http_client_/ar_http_request_util.py → arpakitlib-3.0.4/arpakitlib/common_/http_request_util.py +5 -4
  11. arpakitlib-3.0.2/arpakitlib/common_/ar_json_db_util.py → arpakitlib-3.0.4/arpakitlib/common_/json_db_util.py +2 -2
  12. arpakitlib-3.0.2/arpakitlib/common_/ar_log_async_func_if_error_util.py → arpakitlib-3.0.4/arpakitlib/common_/log_async_func_if_error_util.py +1 -1
  13. arpakitlib-3.0.2/arpakitlib/common_/ar_parse_command_util.py → arpakitlib-3.0.4/arpakitlib/common_/parse_command_util.py +2 -1
  14. arpakitlib-3.0.2/arpakitlib/common_/ar_rat_func_util.py → arpakitlib-3.0.4/arpakitlib/common_/rat_func_util.py +2 -1
  15. arpakitlib-3.0.2/arpakitlib/common_/ar_retry_func_util.py → arpakitlib-3.0.4/arpakitlib/common_/retry_func_util.py +1 -1
  16. arpakitlib-3.0.2/arpakitlib/sqladmin_/ar_sqladmin_etc_util.py → arpakitlib-3.0.4/arpakitlib/sqladmin_/sqladmin_model_view_info.py +9 -9
  17. arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_pydantic_schema_from_sqlalchemy_model_util.py → arpakitlib-3.0.4/arpakitlib/sqlalchemy_/pydantic_schema_from_sqlalchemy_model_util.py +2 -1
  18. arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_db_util.py → arpakitlib-3.0.4/arpakitlib/sqlalchemy_/sqlalchemy_db_util.py +5 -4
  19. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/pyproject.toml +1 -1
  20. arpakitlib-3.0.2/arpakitlib/aiogram_/ar_aiogram_as_tg_command_util.py +0 -190
  21. arpakitlib-3.0.2/arpakitlib/aiogram_/ar_include_aiogram_routers_from_dir_util.py +0 -34
  22. arpakitlib-3.0.2/arpakitlib/fastapi_/ar_include_fastapi_routers_from_dir_util.py +0 -37
  23. arpakitlib-3.0.2/arpakitlib/http_client_/__init__.py +0 -1
  24. arpakitlib-3.0.2/arpakitlib/pydantic_/__init__.py +0 -1
  25. arpakitlib-3.0.2/arpakitlib/sqladmin_/__init__.py +0 -1
  26. arpakitlib-3.0.2/arpakitlib/sqlalchemy_/__init__.py +0 -1
  27. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/LICENSE +0 -0
  28. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/arpakitlib/__init__.py +0 -0
  29. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/arpakitlib/aiogram_/__init__.py +0 -0
  30. {arpakitlib-3.0.2 → arpakitlib-3.0.4}/arpakitlib/common_/__init__.py +0 -0
  31. /arpakitlib-3.0.2/arpakitlib/common_/ar_base64_util.py → /arpakitlib-3.0.4/arpakitlib/common_/base64_util.py +0 -0
  32. /arpakitlib-3.0.2/arpakitlib/pydantic_/ar_clone_pydantic_model_fields_util.py → /arpakitlib-3.0.4/arpakitlib/common_/clone_pydantic_model_fields_util.py +0 -0
  33. /arpakitlib-3.0.2/arpakitlib/common_/ar_datetime_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/datetime_etc_util.py +0 -0
  34. /arpakitlib-3.0.2/arpakitlib/common_/ar_dict_util.py → /arpakitlib-3.0.4/arpakitlib/common_/dict_util.py +0 -0
  35. /arpakitlib-3.0.2/arpakitlib/common_/ar_enumeration_util.py → /arpakitlib-3.0.4/arpakitlib/common_/enumeration_util.py +0 -0
  36. /arpakitlib-3.0.2/arpakitlib/common_/ar_exception_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/exception_etc_util.py +0 -0
  37. /arpakitlib-3.0.2/arpakitlib/common_/ar_func_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/func_etc_util.py +0 -0
  38. /arpakitlib-3.0.2/arpakitlib/common_/ar_generate_connection_url_util.py → /arpakitlib-3.0.4/arpakitlib/common_/generate_connection_url_util.py +0 -0
  39. /arpakitlib-3.0.2/arpakitlib/common_/ar_generate_difficult_password_util.py → /arpakitlib-3.0.4/arpakitlib/common_/generate_difficult_password_util.py +0 -0
  40. /arpakitlib-3.0.2/arpakitlib/common_/ar_generate_simple_code_util.py → /arpakitlib-3.0.4/arpakitlib/common_/generate_simple_code_util.py +0 -0
  41. /arpakitlib-3.0.2/arpakitlib/common_/ar_ip_util.py → /arpakitlib-3.0.4/arpakitlib/common_/ip_util.py +0 -0
  42. /arpakitlib-3.0.2/arpakitlib/common_/ar_json_util.py → /arpakitlib-3.0.4/arpakitlib/common_/json_util.py +0 -0
  43. /arpakitlib-3.0.2/arpakitlib/common_/ar_logging_util.py → /arpakitlib-3.0.4/arpakitlib/common_/logging_util.py +0 -0
  44. /arpakitlib-3.0.2/arpakitlib/etc_/ar_make_zip_with_passwd_util.py → /arpakitlib-3.0.4/arpakitlib/common_/make_zip_with_passwd_util.py +0 -0
  45. /arpakitlib-3.0.2/arpakitlib/common_/ar_not_set_util.py → /arpakitlib-3.0.4/arpakitlib/common_/not_set_util.py +0 -0
  46. /arpakitlib-3.0.2/arpakitlib/etc_/ar_postgresql_db_dump_util.py → /arpakitlib-3.0.4/arpakitlib/common_/postgresql_db_dump_util.py +0 -0
  47. /arpakitlib-3.0.2/arpakitlib/etc_/ar_really_validate_email_util.py → /arpakitlib-3.0.4/arpakitlib/common_/really_validate_email_util.py +0 -0
  48. /arpakitlib-3.0.2/arpakitlib/common_/ar_run_cmd_util.py → /arpakitlib-3.0.4/arpakitlib/common_/run_cmd_util.py +0 -0
  49. /arpakitlib-3.0.2/arpakitlib/common_/ar_safe_sleep_util.py → /arpakitlib-3.0.4/arpakitlib/common_/safe_sleep_util.py +0 -0
  50. /arpakitlib-3.0.2/arpakitlib/common_/ar_simple_settings_util.py → /arpakitlib-3.0.4/arpakitlib/common_/simple_settings_util.py +0 -0
  51. /arpakitlib-3.0.2/arpakitlib/common_/ar_str_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/str_etc_util.py +0 -0
  52. /arpakitlib-3.0.2/arpakitlib/common_/ar_type_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/type_etc_util.py +0 -0
  53. /arpakitlib-3.0.2/arpakitlib/common_/ar_typed_objects_from_dir_util.py → /arpakitlib-3.0.4/arpakitlib/common_/typed_objects_from_dir_util.py +0 -0
  54. /arpakitlib-3.0.2/arpakitlib/common_/ar_uuid_etc_util.py → /arpakitlib-3.0.4/arpakitlib/common_/uuid_etc_util.py +0 -0
  55. {arpakitlib-3.0.2/arpakitlib/etc_ → arpakitlib-3.0.4/arpakitlib/sqladmin_}/__init__.py +0 -0
  56. {arpakitlib-3.0.2/arpakitlib/fastapi_ → arpakitlib-3.0.4/arpakitlib/sqlalchemy_}/__init__.py +0 -0
  57. /arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_base_dbm_util.py → /arpakitlib-3.0.4/arpakitlib/sqlalchemy_/sqlalchemy_base_dbm_util.py +0 -0
  58. /arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_declarative_base_info_util.py → /arpakitlib-3.0.4/arpakitlib/sqlalchemy_/sqlalchemy_declarative_base_info_util.py +0 -0
  59. /arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_drop_check_constraints_util.py → /arpakitlib-3.0.4/arpakitlib/sqlalchemy_/sqlalchemy_drop_check_constraints_util.py +0 -0
  60. /arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_ensure_check_constraints_util.py → /arpakitlib-3.0.4/arpakitlib/sqlalchemy_/sqlalchemy_ensure_check_constraints_util.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: arpakitlib
3
- Version: 3.0.2
3
+ Version: 3.0.4
4
4
  Summary: Lightweight and convenient development tools by ARPAKIT Company
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -56,23 +56,20 @@ your workflow.
56
56
 
57
57
  ### What is inside
58
58
 
59
- Utilities are grouped by the library they build on, so you only reach for what your project already uses:
59
+ A set of small, self-contained utilities you pick from one at a time:
60
60
 
61
- | Package | About |
62
- |---|---|
63
- | `arpakitlib.common_` | Everyday helpers: JSON, dates, files, settings, workers, retries, enumerations |
64
- | `arpakitlib.sqlalchemy_` | Declarative base with handy introspection, database helper, check constraints |
65
- | `arpakitlib.pydantic_` | Building schemas out of existing pydantic models |
66
- | `arpakitlib.http_client_` | Sync and async HTTP requests with retries, proxy support and a base API client |
67
- | `arpakitlib.fastapi_` | Collecting routers from a directory |
68
- | `arpakitlib.aiogram_` | Collecting routers from a directory, parsing Telegram commands |
69
- | `arpakitlib.sqladmin_` | Introspection for admin model views |
70
- | `arpakitlib.etc_` | Everything else: password protected archives, database dumps, email validation |
61
+ - **Everyday helpers** — JSON, dates, strings, dictionaries, files, settings, background workers, retries, enumerations
62
+ - **Databases** — declarative base with introspection, database helper, check constraints, schemas from existing models
63
+ - **HTTP** — sync and async requests with retries and proxy support, plus a base API client
64
+ - **Telegram bots** — parsing commands
65
+ - **Admin panels** — introspection for admin model views
66
+ - **Operations** — password protected archives, database dumps, shell commands, email validation
71
67
 
72
- Every module keeps its own runnable example, so the fastest way to see what a utility does is to run it:
68
+ Every module keeps its own runnable example, so the fastest way to see what a utility does is to run that
69
+ module directly:
73
70
 
74
71
  ```bash
75
- python -m arpakitlib.common_.ar_json_util
72
+ python -m arpakitlib.<package>.<module>
76
73
  ```
77
74
 
78
75
  ---
@@ -123,7 +120,7 @@ pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://
123
120
  from datetime import datetime
124
121
  from decimal import Decimal
125
122
 
126
- from arpakitlib.common_.ar_json_util import transfer_data_to_json_str
123
+ from arpakitlib.common_.json_util import transfer_data_to_json_str
127
124
 
128
125
  print(transfer_data_to_json_str({"when": datetime(2026, 9, 4), "price": Decimal("1.5")}))
129
126
  # {
@@ -13,23 +13,20 @@ your workflow.
13
13
 
14
14
  ### What is inside
15
15
 
16
- Utilities are grouped by the library they build on, so you only reach for what your project already uses:
16
+ A set of small, self-contained utilities you pick from one at a time:
17
17
 
18
- | Package | About |
19
- |---|---|
20
- | `arpakitlib.common_` | Everyday helpers: JSON, dates, files, settings, workers, retries, enumerations |
21
- | `arpakitlib.sqlalchemy_` | Declarative base with handy introspection, database helper, check constraints |
22
- | `arpakitlib.pydantic_` | Building schemas out of existing pydantic models |
23
- | `arpakitlib.http_client_` | Sync and async HTTP requests with retries, proxy support and a base API client |
24
- | `arpakitlib.fastapi_` | Collecting routers from a directory |
25
- | `arpakitlib.aiogram_` | Collecting routers from a directory, parsing Telegram commands |
26
- | `arpakitlib.sqladmin_` | Introspection for admin model views |
27
- | `arpakitlib.etc_` | Everything else: password protected archives, database dumps, email validation |
18
+ - **Everyday helpers** — JSON, dates, strings, dictionaries, files, settings, background workers, retries, enumerations
19
+ - **Databases** — declarative base with introspection, database helper, check constraints, schemas from existing models
20
+ - **HTTP** — sync and async requests with retries and proxy support, plus a base API client
21
+ - **Telegram bots** — parsing commands
22
+ - **Admin panels** — introspection for admin model views
23
+ - **Operations** — password protected archives, database dumps, shell commands, email validation
28
24
 
29
- Every module keeps its own runnable example, so the fastest way to see what a utility does is to run it:
25
+ Every module keeps its own runnable example, so the fastest way to see what a utility does is to run that
26
+ module directly:
30
27
 
31
28
  ```bash
32
- python -m arpakitlib.common_.ar_json_util
29
+ python -m arpakitlib.<package>.<module>
33
30
  ```
34
31
 
35
32
  ---
@@ -80,7 +77,7 @@ pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://
80
77
  from datetime import datetime
81
78
  from decimal import Decimal
82
79
 
83
- from arpakitlib.common_.ar_json_util import transfer_data_to_json_str
80
+ from arpakitlib.common_.json_util import transfer_data_to_json_str
84
81
 
85
82
  print(transfer_data_to_json_str({"when": datetime(2026, 9, 4), "price": Decimal("1.5")}))
86
83
  # {
@@ -0,0 +1,279 @@
1
+ # arpakit
2
+
3
+ import ast
4
+ import asyncio
5
+ import html
6
+ import json
7
+ import logging
8
+ from typing import Any, get_origin, get_args, Awaitable, Callable
9
+
10
+ from aiogram import types
11
+ from aiogram.enums import ParseMode
12
+ from aiogram.filters import CommandObject
13
+ from pydantic import BaseModel, Field, ConfigDict
14
+
15
+ from arpakitlib.common_.parse_command_util import parse_command
16
+
17
+ _logger = logging.getLogger(__name__)
18
+
19
+ # Telegram отклоняет сообщение целиком, если текст длиннее лимита или в нём битая HTML-разметка
20
+ _TG_MAX_TEXT_LEN = 4096
21
+ _MAX_EXCEPTION_LEN = 512
22
+ _MAX_DESC_LEN = 512
23
+ _MAX_FIELD_DESC_LEN = 128
24
+ _MAX_DEFAULT_LEN = 64
25
+
26
+
27
+ def _cut(text: str, *, max_len: int) -> str:
28
+ return text if len(text) <= max_len else text[:max_len] + "…"
29
+
30
+
31
+ class BaseTgCommandModel(BaseModel):
32
+ model_config = ConfigDict(extra="ignore", arbitrary_types_allowed=True, from_attributes=True)
33
+
34
+ help: bool | None = Field(default=False)
35
+
36
+
37
+ class ExampleTgCommandModel(BaseTgCommandModel):
38
+ """Это описание команды hello-world"""
39
+
40
+ hello: str | None = Field(description="Example Desc", default="Hello world")
41
+
42
+
43
+ def _type_name(annotation: Any) -> str:
44
+ origin = get_origin(annotation)
45
+ args = get_args(annotation)
46
+
47
+ if origin is list and args:
48
+ return f"list[{_type_name(args[0])}]"
49
+ if hasattr(annotation, "__name__"):
50
+ return annotation.__name__
51
+ return str(annotation)
52
+
53
+
54
+ def _render_field_line(*, name: str, field: Any) -> str:
55
+ type_name = html.escape(_cut(_type_name(field.annotation), max_len=_MAX_DEFAULT_LEN))
56
+
57
+ description = ""
58
+ if field.description:
59
+ description = f" — {html.escape(_cut(field.description, max_len=_MAX_FIELD_DESC_LEN))}"
60
+
61
+ # is_required учитывает default_factory, в отличие от сравнения default с PydanticUndefined
62
+ if field.is_required():
63
+ tail = " <i>(required)</i>"
64
+ else:
65
+ try:
66
+ # у поля с default_factory сам default равен PydanticUndefined, значение даёт только вызов фабрики
67
+ default = field.get_default(call_default_factory=True)
68
+ tail = f" (default: {html.escape(_cut(str(default), max_len=_MAX_DEFAULT_LEN))})"
69
+ except Exception:
70
+ # фабрике нужны значения других полей — конкретный дефолт тут не получить
71
+ tail = " <i>(default from factory)</i>"
72
+
73
+ name = html.escape(_cut(name, max_len=_MAX_DEFAULT_LEN))
74
+
75
+ return f"\n• <code>-{name}</code>: <i>{type_name}</i>{description}{tail}"
76
+
77
+
78
+ def _generate_help_text(
79
+ *,
80
+ command_name: str,
81
+ model_class: type[BaseTgCommandModel],
82
+ desc: str | None = None
83
+ ) -> str:
84
+ """Генерирует help-текст по описанию модели."""
85
+ command_name = html.escape(_cut(command_name, max_len=_MAX_DEFAULT_LEN))
86
+
87
+ lines = [f"<b>Command</b> /{command_name}"]
88
+
89
+ # описание не передали явно — берём докстроку модели
90
+ if desc is None:
91
+ desc = model_class.__doc__
92
+ if desc:
93
+ desc = desc.strip()
94
+ if desc:
95
+ lines.append(f"\n{html.escape(_cut(desc, max_len=_MAX_DESC_LEN))}")
96
+
97
+ model_fields = model_class.model_fields
98
+ lines.append(f"\n\n<b>Fields ({len(model_fields)}):</b>")
99
+
100
+ footer = (
101
+ f"\n\n<b>Usage for help:</b>"
102
+ f"\n<code>/{command_name} -help</code> or <code>/{command_name} -h</code>"
103
+ )
104
+
105
+ # место под пометку об обрезке резервируем заранее, по худшему случаю
106
+ reserve = len(f"\n\n<i>… and {len(model_fields)} more fields</i>") + 1
107
+
108
+ # обрезаем по границам строк: каждая строка закрывает свои теги, поэтому разметка не ломается.
109
+ # used — длина итогового текста, если оборвать список прямо сейчас, вместе с футером и join-переносами
110
+ used = len("\n".join(lines)) + 1 + len(footer)
111
+ for number, (name, field) in enumerate(model_fields.items()):
112
+ line = _render_field_line(name=name, field=field)
113
+ if used + 1 + len(line) > _TG_MAX_TEXT_LEN - reserve:
114
+ left = len(model_fields) - number
115
+ lines.append(f"\n\n<i>… and {left} more field{'s' if left != 1 else ''}</i>")
116
+ break
117
+ lines.append(line)
118
+ used += 1 + len(line)
119
+
120
+ lines.append(footer)
121
+
122
+ return "\n".join(lines)
123
+
124
+
125
+ def _generate_error_text(*, command_name: str, exception: Exception) -> str:
126
+ """Генерирует текст ответа на команду, которую не удалось разобрать."""
127
+ command_name = html.escape(_cut(command_name, max_len=_MAX_DEFAULT_LEN))
128
+ exception_text = html.escape(_cut(str(exception).strip(), max_len=_MAX_EXCEPTION_LEN))
129
+
130
+ return (
131
+ f"<b>Bad command usage</b> /{command_name}"
132
+ f"\n"
133
+ f"\n<b>Error:</b>"
134
+ f"\n{exception_text}"
135
+ f"\n"
136
+ f"\nUse <code>/{command_name} -help</code> for help info"
137
+ )
138
+
139
+
140
+ def _parse_tg_param(value: Any) -> Any:
141
+ """Интеллектуальное преобразование строки из Telegram-команды в Python-значение."""
142
+ if isinstance(value, (bool, int, float)) or value is None:
143
+ return value
144
+
145
+ v = value.strip()
146
+ if v.lower() in {"true", "false"}:
147
+ return v.lower() == "true"
148
+
149
+ try:
150
+ result = ast.literal_eval(v)
151
+ # Если получился список — проверим, не смесь ли типов
152
+ if isinstance(result, list):
153
+ # Если все элементы одного типа — оставляем
154
+ if len(result) > 0 and len({type(x) for x in result}) > 1:
155
+ # Приводим всё к строкам для единообразия
156
+ result = [str(x) for x in result]
157
+ return result
158
+ except Exception:
159
+ # не литерал Python — пробуем JSON, он покрывает true/false/null внутри структур
160
+ pass
161
+
162
+ try:
163
+ result = json.loads(v)
164
+ return result
165
+ except Exception:
166
+ pass
167
+
168
+ return v
169
+
170
+
171
+ def as_tg_command_handler(
172
+ *,
173
+ tg_command_format_class: type[BaseTgCommandModel],
174
+ desc: str | None = None
175
+ ) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]:
176
+ def decorator(handler):
177
+
178
+ # functools.wraps здесь намеренно не нужен: inspect.signature пошла бы по __wrapped__
179
+ # к исходному хендлеру, и aiogram перестал бы прокидывать command, нужный обёртке
180
+ async def new_handler(*args, **kwargs):
181
+
182
+ if not args:
183
+ raise TypeError("handler called without positional message")
184
+
185
+ message: types.Message = args[0]
186
+ if not isinstance(message, types.Message):
187
+ raise TypeError("not isinstance(message, types.Message)")
188
+
189
+ tg_command: CommandObject = kwargs.get("command")
190
+ if tg_command is None:
191
+ raise ValueError("Missing 'command' in handler kwargs")
192
+
193
+ try:
194
+
195
+ parsed_command = parse_command(text=tg_command.text)
196
+ kwargs["parsed_command"] = parsed_command
197
+
198
+ if parsed_command.has_flag(flag="help") or parsed_command.has_flag(flag="h"):
199
+ await message.answer(
200
+ text=_generate_help_text(
201
+ command_name=tg_command.command,
202
+ model_class=tg_command_format_class,
203
+ desc=desc
204
+ ),
205
+ disable_web_page_preview=True,
206
+ parse_mode=ParseMode.HTML
207
+ )
208
+ return None
209
+
210
+ tg_command_model_data: dict[str, Any] = {}
211
+
212
+ for key, value in parsed_command.key_to_value.items():
213
+ if value is None:
214
+ tg_command_model_data[key] = True
215
+ else:
216
+ tg_command_model_data[key] = _parse_tg_param(value=value)
217
+
218
+ for i, value in enumerate(parsed_command.values_without_key):
219
+ tg_command_model_data[f"arg_{i}"] = _parse_tg_param(value=value)
220
+
221
+ tg_command_format_obj = tg_command_format_class(**tg_command_model_data)
222
+
223
+ kwargs["tg_command_format_obj"] = tg_command_format_obj
224
+
225
+ except Exception as exception:
226
+
227
+ _logger.exception("Error while parsing command %s", tg_command.text)
228
+
229
+ await message.answer(
230
+ text=_generate_error_text(
231
+ command_name=tg_command.command,
232
+ exception=exception
233
+ ),
234
+ disable_web_page_preview=True,
235
+ parse_mode=ParseMode.HTML
236
+ )
237
+
238
+ return None
239
+
240
+ return await handler(*args, **kwargs)
241
+
242
+ return new_handler
243
+
244
+ return decorator
245
+
246
+
247
+ def __example():
248
+ print("--- help-текст по модели ---")
249
+ print(_generate_help_text(command_name="hello-world", model_class=ExampleTgCommandModel))
250
+
251
+ print("\n--- описание и значения экранируются ---")
252
+
253
+ class DangerousTgCommandModel(BaseTgCommandModel):
254
+ """Ставит лимит <b>жирным</b> шрифтом"""
255
+
256
+ limit: int = Field(description="должен быть < 100")
257
+
258
+ print(_generate_help_text(command_name="set", model_class=DangerousTgCommandModel))
259
+
260
+ print("\n--- текст ошибки тоже экранируется ---")
261
+ print(_generate_error_text(
262
+ command_name="set",
263
+ exception=ValueError("expected <class 'str'>, got int: 123")
264
+ ))
265
+
266
+ print("\n--- разбор значений из команды ---")
267
+ samples = ["123", "true", "3.14", "None", "[1, 2, 3]", "[1, 'a']", '{"a": true}', "hello world"]
268
+ for sample in samples:
269
+ result = _parse_tg_param(value=sample)
270
+ print(f"{sample!r:16} -> {result!r} ({type(result).__name__})")
271
+
272
+
273
+ async def __async_example():
274
+ pass
275
+
276
+
277
+ if __name__ == '__main__':
278
+ __example()
279
+ asyncio.run(__async_example())
@@ -6,8 +6,9 @@ from typing import Any
6
6
 
7
7
  import aiohttp
8
8
  import requests
9
- from arpakitlib.common_.ar_dict_util import combine_dicts
10
- from arpakitlib.http_client_.ar_http_request_util import async_make_http_request, sync_make_http_request
9
+
10
+ from arpakitlib.common_.dict_util import combine_dicts
11
+ from arpakitlib.common_.http_request_util import async_make_http_request, sync_make_http_request
11
12
 
12
13
 
13
14
  class BaseHTTPAPIClient:
@@ -8,9 +8,9 @@ from datetime import timedelta
8
8
  from typing import Any
9
9
  from uuid import uuid4
10
10
 
11
- from arpakitlib.common_.ar_enumeration_util import Enumeration
12
- from arpakitlib.common_.ar_func_etc_util import is_async_func, is_sync_func
13
- from arpakitlib.common_.ar_safe_sleep_util import async_safe_sleep, sync_safe_sleep
11
+ from arpakitlib.common_.enumeration_util import Enumeration
12
+ from arpakitlib.common_.func_etc_util import is_async_func, is_sync_func
13
+ from arpakitlib.common_.safe_sleep_util import async_safe_sleep, sync_safe_sleep
14
14
 
15
15
  BackgroundHandle = asyncio.Task[None] | threading.Thread | multiprocessing.Process
16
16
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  import asyncio
4
4
 
5
- from arpakitlib.common_.ar_enumeration_util import Enumeration
5
+ from arpakitlib.common_.enumeration_util import Enumeration
6
6
 
7
7
 
8
8
  class BaseBlank:
@@ -4,11 +4,12 @@ import asyncio
4
4
  from datetime import datetime
5
5
  from typing import Any
6
6
 
7
- from arpakitlib.common_.ar_datetime_etc_util import UTC, now_utc_dt
8
- from arpakitlib.common_.ar_json_db_util import JSONDbFile
9
- from arpakitlib.common_.ar_type_etc_util import raise_for_type
10
7
  from pydantic import BaseModel
11
8
 
9
+ from arpakitlib.common_.datetime_etc_util import UTC, now_utc_dt
10
+ from arpakitlib.common_.json_db_util import JSONDbFile
11
+ from arpakitlib.common_.type_etc_util import raise_for_type
12
+
12
13
 
13
14
  class CacheBlock(BaseModel):
14
15
  key: str
@@ -3,7 +3,7 @@
3
3
  import asyncio
4
4
  from typing import Any
5
5
 
6
- from arpakitlib.common_.ar_json_util import transfer_data_to_json_str
6
+ from arpakitlib.common_.json_util import transfer_data_to_json_str
7
7
 
8
8
 
9
9
  class DictAsObject:
@@ -7,8 +7,8 @@ import shutil
7
7
  import uuid
8
8
  from typing import Optional, Union, Iterator
9
9
 
10
- from arpakitlib.common_.ar_datetime_etc_util import now_utc_dt
11
- from arpakitlib.common_.ar_str_etc_util import make_none_if_blank
10
+ from arpakitlib.common_.datetime_etc_util import now_utc_dt
11
+ from arpakitlib.common_.str_etc_util import make_none_if_blank
12
12
 
13
13
 
14
14
  class FileStorageInDir:
@@ -8,8 +8,9 @@ from typing import Any
8
8
  import aiohttp
9
9
  import requests
10
10
  from aiohttp_socks import ProxyConnector
11
- from arpakitlib.common_.ar_json_util import transfer_data_to_json_str
12
- from arpakitlib.common_.ar_safe_sleep_util import sync_safe_sleep, async_safe_sleep
11
+
12
+ from arpakitlib.common_.json_util import transfer_data_to_json_str
13
+ from arpakitlib.common_.safe_sleep_util import sync_safe_sleep, async_safe_sleep
13
14
 
14
15
  _logger = logging.getLogger(__name__)
15
16
 
@@ -57,7 +58,7 @@ def sync_make_http_request(
57
58
  if json is not None:
58
59
  if "data" in kwargs or "json" in kwargs:
59
60
  raise ValueError("json is used together with data/json in kwargs, choose one")
60
- # сериализуем сами, чтобы datetime/Decimal/UUID и NaN вели себя как в ar_json_util
61
+ # сериализуем сами, чтобы datetime/Decimal/UUID и NaN вели себя как в json_util
61
62
  kwargs["data"] = transfer_data_to_json_str(data=json, beautify=False).encode("utf-8")
62
63
  headers = dict(headers) if headers else {}
63
64
  if not any(key.lower() == "content-type" for key in headers):
@@ -150,7 +151,7 @@ async def async_make_http_request(
150
151
  if json is not None:
151
152
  if "data" in kwargs or "json" in kwargs:
152
153
  raise ValueError("json is used together with data/json in kwargs, choose one")
153
- # сериализуем сами, чтобы datetime/Decimal/UUID и NaN вели себя как в ar_json_util
154
+ # сериализуем сами, чтобы datetime/Decimal/UUID и NaN вели себя как в json_util
154
155
  kwargs["data"] = transfer_data_to_json_str(data=json, beautify=False).encode("utf-8")
155
156
  headers = dict(headers) if headers else {}
156
157
  if not any(key.lower() == "content-type" for key in headers):
@@ -5,8 +5,8 @@ import os
5
5
  import shutil
6
6
  from typing import Any, Self
7
7
 
8
- from arpakitlib.common_.ar_json_util import transfer_data_to_json_str, transfer_json_str_to_data
9
- from arpakitlib.common_.ar_type_etc_util import raise_for_type
8
+ from arpakitlib.common_.json_util import transfer_data_to_json_str, transfer_json_str_to_data
9
+ from arpakitlib.common_.type_etc_util import raise_for_type
10
10
 
11
11
 
12
12
  class JSONDbFile:
@@ -5,7 +5,7 @@ import logging
5
5
  from collections.abc import Awaitable, Callable
6
6
  from typing import Any
7
7
 
8
- from arpakitlib.common_.ar_func_etc_util import get_func_name
8
+ from arpakitlib.common_.func_etc_util import get_func_name
9
9
 
10
10
 
11
11
  async def log_async_func_if_error(
@@ -4,9 +4,10 @@ import asyncio
4
4
  import os
5
5
  import shlex
6
6
 
7
- from arpakitlib.common_.ar_type_etc_util import raise_for_type
8
7
  from pydantic import BaseModel, Field
9
8
 
9
+ from arpakitlib.common_.type_etc_util import raise_for_type
10
+
10
11
 
11
12
  class BadCommandFormat(Exception):
12
13
  pass
@@ -3,9 +3,10 @@
3
3
  import asyncio
4
4
  from typing import Any, Callable, Awaitable
5
5
 
6
- from arpakitlib.common_.ar_func_etc_util import get_func_name
7
6
  from pydantic import BaseModel, ConfigDict
8
7
 
8
+ from arpakitlib.common_.func_etc_util import get_func_name
9
+
9
10
 
10
11
  class RatFuncRes(BaseModel):
11
12
  model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True, from_attributes=True)
@@ -5,7 +5,7 @@ from collections.abc import Awaitable, Callable
5
5
  from datetime import timedelta
6
6
  from typing import Any
7
7
 
8
- from arpakitlib.common_.ar_safe_sleep_util import async_safe_sleep, sync_safe_sleep
8
+ from arpakitlib.common_.safe_sleep_util import async_safe_sleep, sync_safe_sleep
9
9
 
10
10
 
11
11
  def _raise_if_bad_max_tries(max_tries: int):
@@ -19,18 +19,18 @@ def _column_list_item_name(v: Any) -> str:
19
19
  raise TypeError(f"unknown type, {type(v)=}")
20
20
 
21
21
 
22
- def iter_all_subclasses(class_: type[ModelView]) -> Iterator[type[ModelView]]:
22
+ def _iter_all_subclasses(class_: type[ModelView]) -> Iterator[type[ModelView]]:
23
23
  # именно рекурсивно: __subclasses__() отдаёт только прямых потомков, а вьюхи
24
24
  # почти всегда наследуются через общий промежуточный класс
25
25
  for subclass in class_.__subclasses__():
26
26
  yield subclass
27
- yield from iter_all_subclasses(subclass)
27
+ yield from _iter_all_subclasses(subclass)
28
28
 
29
29
 
30
- def get_model_views(class_: type[ModelView]) -> list[type[ModelView]]:
30
+ def _get_model_views(class_: type[ModelView]) -> list[type[ModelView]]:
31
31
  """Вьюхи, у которых есть модель. Промежуточные базовые классы пропускаем."""
32
32
  res: list[type[ModelView]] = []
33
- for subclass in iter_all_subclasses(class_):
33
+ for subclass in _iter_all_subclasses(class_):
34
34
  if subclass in res:
35
35
  continue
36
36
  if getattr(subclass, "model", None) is None:
@@ -39,8 +39,8 @@ def get_model_views(class_: type[ModelView]) -> list[type[ModelView]]:
39
39
  return sorted(res, key=lambda model_view: model_view.__name__)
40
40
 
41
41
 
42
- def get_string_info_from_model_view(class_: type[ModelView]) -> str:
43
- model_views = get_model_views(class_)
42
+ def get_sqladmin_model_view_info(class_: type[ModelView]) -> str:
43
+ model_views = _get_model_views(class_)
44
44
 
45
45
  lines = [f"ModelViews: {len(model_views)}"]
46
46
  for i, model_view in enumerate(model_views, start=1):
@@ -58,7 +58,7 @@ def __example():
58
58
  from sqlalchemy import Integer, String
59
59
  from sqlalchemy.orm import Mapped, mapped_column
60
60
 
61
- from arpakitlib.sqlalchemy_.ar_sqlalchemy_base_dbm_util import BaseDBM
61
+ from arpakitlib.sqlalchemy_.sqlalchemy_base_dbm_util import BaseDBM
62
62
 
63
63
  class UserDBM(BaseDBM):
64
64
  __tablename__ = "example_model_view_users"
@@ -80,9 +80,9 @@ def __example():
80
80
  column_list = ["id"]
81
81
 
82
82
  print(f"прямые подклассы ModelView: {[c.__name__ for c in ModelView.__subclasses__()]}")
83
- print(f"найдено вьюх: {[c.__name__ for c in get_model_views(ModelView)]}")
83
+ print(f"найдено вьюх: {[c.__name__ for c in _get_model_views(ModelView)]}")
84
84
  print()
85
- print(get_string_info_from_model_view(ModelView))
85
+ print(get_sqladmin_model_view_info(ModelView))
86
86
 
87
87
 
88
88
  async def __async_example():
@@ -4,11 +4,12 @@ import asyncio
4
4
  from collections.abc import Collection
5
5
  from typing import Any, get_args, get_origin, get_type_hints
6
6
 
7
- from arpakitlib.sqlalchemy_.ar_sqlalchemy_base_dbm_util import BaseDBM, _raise_for_str_collections
8
7
  from pydantic import BaseModel
9
8
  from sqlalchemy import inspect
10
9
  from sqlalchemy.orm import Mapped
11
10
 
11
+ from arpakitlib.sqlalchemy_.sqlalchemy_base_dbm_util import BaseDBM, _raise_for_str_collections
12
+
12
13
 
13
14
  def _get_mapped_annotations(sqlalchemy_model: type[BaseDBM]) -> dict[str, Any]:
14
15
  """
@@ -7,13 +7,14 @@ from typing import Any
7
7
  from uuid import uuid4
8
8
 
9
9
  import sqlalchemy
10
- from arpakitlib.common_.ar_datetime_etc_util import now_utc_dt
11
- from arpakitlib.sqlalchemy_.ar_sqlalchemy_base_dbm_util import BaseDBM
12
10
  from sqlalchemy import create_engine, QueuePool, text, func, inspect, AsyncAdaptedQueuePool
13
11
  from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
14
12
  from sqlalchemy.orm import sessionmaker
15
13
  from sqlalchemy.orm.session import Session
16
14
 
15
+ from arpakitlib.common_.datetime_etc_util import now_utc_dt
16
+ from arpakitlib.sqlalchemy_.sqlalchemy_base_dbm_util import BaseDBM
17
+
17
18
 
18
19
  class SQLAlchemyDb:
19
20
  def __init__(
@@ -109,12 +110,12 @@ class SQLAlchemyDb:
109
110
  self._logger.info("alembic tables data were removed")
110
111
 
111
112
  def ensure_check_constraints(self):
112
- from arpakitlib.sqlalchemy_.ar_sqlalchemy_ensure_check_constraints_util import \
113
+ from arpakitlib.sqlalchemy_.sqlalchemy_ensure_check_constraints_util import \
113
114
  ensure_sqlalchemy_check_constraints
114
115
  ensure_sqlalchemy_check_constraints(base_=self.base_dbm, engine=self.engine)
115
116
 
116
117
  def drop_check_constraints(self):
117
- from arpakitlib.sqlalchemy_.ar_sqlalchemy_drop_check_constraints_util import drop_sqlalchemy_check_constraints
118
+ from arpakitlib.sqlalchemy_.sqlalchemy_drop_check_constraints_util import drop_sqlalchemy_check_constraints
118
119
  drop_sqlalchemy_check_constraints(base_=self.base_dbm, engine=self.engine)
119
120
 
120
121
  def drop_and_ensure_check_constraints(self):
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "arpakitlib"
3
- version = "3.0.2"
3
+ version = "3.0.4"
4
4
  description = "Lightweight and convenient development tools by ARPAKIT Company"
5
5
  authors = [
6
6
  { name = "arpakit_company", email = "support@arpakit.com" }
@@ -1,190 +0,0 @@
1
- # arpakit
2
-
3
- import ast
4
- import asyncio
5
- import json
6
- import logging
7
- from typing import Any, get_origin, get_args, Awaitable, Callable
8
-
9
- from aiogram import types
10
- from aiogram.enums import ParseMode
11
- from aiogram.filters import CommandObject
12
- from arpakitlib.common_.ar_parse_command_util import parse_command
13
- from pydantic import BaseModel, Field, ConfigDict
14
- from pydantic_core import PydanticUndefined
15
-
16
- _logger = logging.getLogger(__name__)
17
-
18
-
19
- class BaseTgCommandModel(BaseModel):
20
- model_config = ConfigDict(extra="ignore", arbitrary_types_allowed=True, from_attributes=True)
21
-
22
- help: bool | None = Field(default=False)
23
-
24
-
25
- class ExampleTgCommandModel(BaseTgCommandModel):
26
- """Это описание команды hello-world"""
27
-
28
- hello: str | None = Field(description="Example Desc", default="Hello world")
29
-
30
-
31
- def _generate_help_text(
32
- *,
33
- command_name: str,
34
- model_class: type[BaseTgCommandModel],
35
- desc: str | None = None
36
- ) -> str:
37
- """Генерирует help-текст по описанию модели."""
38
- lines = [f"<b>Command</b> /{command_name}"]
39
-
40
- if desc:
41
- desc = desc.strip()
42
- if desc:
43
- lines.append(f"\n{desc}")
44
-
45
- lines.append(f"\n\n<b>Fields ({len(model_class.model_fields)}):</b>")
46
-
47
- for name, field in model_class.model_fields.items():
48
-
49
- default_value = (
50
- field.default
51
- if field.default is not PydanticUndefined
52
- else "<i>required</i>"
53
- )
54
-
55
- origin = get_origin(field.annotation)
56
- args = get_args(field.annotation)
57
-
58
- if origin is list and args:
59
- type_name = f"list[{args[0].__name__}]"
60
- elif hasattr(field.annotation, "__name__"):
61
- type_name = field.annotation.__name__
62
- else:
63
- type_name = str(field.annotation)
64
-
65
- description = f" — {field.description}" if field.description else ""
66
-
67
- lines.append(f"\n• <code>-{name}</code>: <i>{type_name}</i>{description} (default: {default_value})")
68
-
69
- lines.append(f"\n\n<b>Usage for help:</b>\n<code>/{command_name} -help</code>")
70
-
71
- return "\n".join(lines)
72
-
73
-
74
- def _parse_tg_param(value: Any) -> Any:
75
- """Интеллектуальное преобразование строки из Telegram-команды в Python-значение."""
76
- if isinstance(value, (bool, int, float)) or value is None:
77
- return value
78
-
79
- v = value.strip()
80
- if v.lower() in {"true", "false"}:
81
- return v.lower() == "true"
82
-
83
- try:
84
- result = ast.literal_eval(v)
85
- # Если получился список — проверим, не смесь ли типов
86
- if isinstance(result, list):
87
- # Если все элементы одного типа — оставляем
88
- if len(result) > 0 and len({type(x) for x in result}) > 1:
89
- # Приводим всё к строкам для единообразия
90
- result = [str(x) for x in result]
91
- return result
92
- except Exception:
93
- # не получилось распарсить — возвращаем как строку
94
- pass
95
-
96
- try:
97
- result = json.loads(v)
98
- return result
99
- except Exception:
100
- pass
101
-
102
- return v
103
-
104
-
105
- def as_tg_command_handler(
106
- *,
107
- tg_command_format_class: type[BaseTgCommandModel],
108
- desc: str | None = None
109
- ) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]:
110
- def decorator(handler):
111
-
112
- async def new_handler(*args, **kwargs):
113
-
114
- message: types.Message = args[0]
115
- if not isinstance(message, types.Message):
116
- raise TypeError("not isinstance(message, types.Message)")
117
-
118
- tg_command: CommandObject = kwargs.get("command")
119
- if tg_command is None:
120
- raise ValueError("Missing 'command' in handler kwargs")
121
-
122
- try:
123
-
124
- parsed_command = parse_command(text=tg_command.text)
125
- kwargs["parsed_command"] = parsed_command
126
-
127
- if parsed_command.has_flag(flag="help") or parsed_command.has_flag(flag="h"):
128
- await message.answer(
129
- text=_generate_help_text(
130
- command_name=tg_command.command,
131
- model_class=tg_command_format_class,
132
- desc=desc
133
- ),
134
- disable_web_page_preview=True,
135
- parse_mode=ParseMode.HTML
136
- )
137
- return None
138
-
139
- tg_command_model_data: dict[str, Any] = {}
140
-
141
- for key, value in parsed_command.key_to_value.items():
142
- if value is None:
143
- tg_command_model_data[key] = True
144
- else:
145
- tg_command_model_data[key] = _parse_tg_param(value=value)
146
-
147
- for i, value in enumerate(parsed_command.values_without_key):
148
- tg_command_model_data[f"arg_{i}"] = _parse_tg_param(value=value)
149
-
150
- tg_command_format_obj = tg_command_format_class(**tg_command_model_data)
151
-
152
- kwargs["tg_command_format_obj"] = tg_command_format_obj
153
-
154
- except Exception as exception:
155
-
156
- _logger.exception("Error while parsing command %s", tg_command.text, exc_info=True)
157
-
158
- await message.answer(
159
- text=(
160
- f"<b>Bad command usage</b> /{tg_command.command}"
161
- f"\n"
162
- f"\n<b>Error:</b>"
163
- f"\n{exception}"
164
- f"\n"
165
- f"\nUse <code>/{tg_command.command} -help</code> for help info"
166
- ),
167
- disable_web_page_preview=True,
168
- parse_mode=ParseMode.HTML
169
- )
170
-
171
- return None
172
-
173
- return await handler(*args, **kwargs)
174
-
175
- return new_handler
176
-
177
- return decorator
178
-
179
-
180
- def __example():
181
- pass
182
-
183
-
184
- async def __async_example():
185
- pass
186
-
187
-
188
- if __name__ == '__main__':
189
- __example()
190
- asyncio.run(__async_example())
@@ -1,34 +0,0 @@
1
- # arpakit
2
-
3
- import asyncio
4
-
5
- from aiogram import Router
6
- from arpakitlib.common_.ar_typed_objects_from_dir_util import get_typed_objects_from_dir
7
-
8
-
9
- def include_aiogram_routers_from_dir(
10
- *,
11
- router: Router,
12
- base_dir: str = ".",
13
- exclude_filenames: list[str] | None = None,
14
- ):
15
- for _, tg_bot_router in get_typed_objects_from_dir(
16
- object_type=Router,
17
- attr_name="tg_bot_router",
18
- base_dir=base_dir,
19
- exclude_filenames=["__init__.py", *(exclude_filenames or [])],
20
- ):
21
- router.include_router(tg_bot_router)
22
-
23
-
24
- def __example():
25
- pass
26
-
27
-
28
- async def __async_example():
29
- pass
30
-
31
-
32
- if __name__ == '__main__':
33
- __example()
34
- asyncio.run(__async_example())
@@ -1,37 +0,0 @@
1
- # arpakit
2
-
3
- import asyncio
4
-
5
- from arpakitlib.common_.ar_typed_objects_from_dir_util import get_typed_objects_from_dir
6
- from fastapi import APIRouter
7
-
8
-
9
- def include_fastapi_routers_from_dir(
10
- *,
11
- router: APIRouter,
12
- base_dir: str = ".",
13
- exclude_filenames: list[str] | None = None,
14
- ):
15
- for filename, api_router in get_typed_objects_from_dir(
16
- object_type=APIRouter,
17
- attr_name="api_router",
18
- base_dir=base_dir,
19
- exclude_filenames=["__init__.py", *(exclude_filenames or [])],
20
- ):
21
- router.include_router(
22
- api_router,
23
- prefix="/" + filename.removesuffix(".py"),
24
- )
25
-
26
-
27
- def __example():
28
- pass
29
-
30
-
31
- async def __async_example():
32
- pass
33
-
34
-
35
- if __name__ == '__main__':
36
- __example()
37
- asyncio.run(__async_example())
@@ -1 +0,0 @@
1
- # arpakit
@@ -1 +0,0 @@
1
- # arpakit
@@ -1 +0,0 @@
1
- # arpakit
@@ -1 +0,0 @@
1
- # arpakit
File without changes