arpakitlib 3.0.2__tar.gz → 3.0.10__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.
- {arpakitlib-3.0.2 → arpakitlib-3.0.10}/LICENSE +1 -1
- {arpakitlib-3.0.2 → arpakitlib-3.0.10}/PKG-INFO +67 -36
- arpakitlib-3.0.10/README.md +147 -0
- arpakitlib-3.0.10/arpakitlib/aiogram_util/aiogram_as_tg_command.py +257 -0
- arpakitlib-3.0.2/arpakitlib/common_/ar_base64_util.py → arpakitlib-3.0.10/arpakitlib/common_util/base64_etc.py +18 -68
- arpakitlib-3.0.2/arpakitlib/common_/ar_base_worker_util.py → arpakitlib-3.0.10/arpakitlib/common_util/base_worker.py +5 -75
- arpakitlib-3.0.2/arpakitlib/common_/ar_blank_util.py → arpakitlib-3.0.10/arpakitlib/common_util/blank.py +1 -1
- arpakitlib-3.0.2/arpakitlib/common_/ar_cache_file_util.py → arpakitlib-3.0.10/arpakitlib/common_util/cache_file.py +5 -34
- arpakitlib-3.0.2/arpakitlib/pydantic_/ar_clone_pydantic_model_fields_util.py → arpakitlib-3.0.10/arpakitlib/common_util/clone_pydantic_model_fields.py +1 -52
- arpakitlib-3.0.2/arpakitlib/common_/ar_datetime_etc_util.py → arpakitlib-3.0.10/arpakitlib/common_util/datetime_etc.py +1 -14
- arpakitlib-3.0.2/arpakitlib/common_/ar_dict_as_object_util.py → arpakitlib-3.0.10/arpakitlib/common_util/dict_as_object.py +3 -38
- arpakitlib-3.0.2/arpakitlib/common_/ar_dict_util.py → arpakitlib-3.0.10/arpakitlib/common_util/dict_etc.py +1 -5
- arpakitlib-3.0.2/arpakitlib/common_/ar_logging_util.py → arpakitlib-3.0.10/arpakitlib/common_util/easy_logging.py +1 -13
- arpakitlib-3.0.2/arpakitlib/common_/ar_file_storage_in_dir_util.py → arpakitlib-3.0.10/arpakitlib/common_util/file_storage_in_dir.py +2 -2
- arpakitlib-3.0.2/arpakitlib/common_/ar_func_etc_util.py → arpakitlib-3.0.10/arpakitlib/common_util/func_etc.py +1 -56
- arpakitlib-3.0.10/arpakitlib/common_util/generate_difficult_password.py +52 -0
- arpakitlib-3.0.10/arpakitlib/common_util/generate_simple_code.py +34 -0
- arpakitlib-3.0.2/arpakitlib/common_/ar_json_db_util.py → arpakitlib-3.0.10/arpakitlib/common_util/json_db.py +5 -23
- arpakitlib-3.0.10/arpakitlib/common_util/json_etc.py +92 -0
- arpakitlib-3.0.2/arpakitlib/common_/ar_log_async_func_if_error_util.py → arpakitlib-3.0.10/arpakitlib/common_util/log_async_func_if_error.py +1 -1
- arpakitlib-3.0.2/arpakitlib/common_/ar_not_set_util.py → arpakitlib-3.0.10/arpakitlib/common_util/not_set.py +7 -0
- arpakitlib-3.0.2/arpakitlib/common_/ar_parse_command_util.py → arpakitlib-3.0.10/arpakitlib/common_util/parse_command.py +3 -28
- arpakitlib-3.0.2/arpakitlib/etc_/ar_postgresql_db_dump_util.py → arpakitlib-3.0.10/arpakitlib/common_util/postgresql_db_dump.py +1 -33
- arpakitlib-3.0.2/arpakitlib/common_/ar_rat_func_util.py → arpakitlib-3.0.10/arpakitlib/common_util/rat_func.py +2 -1
- arpakitlib-3.0.2/arpakitlib/etc_/ar_really_validate_email_util.py → arpakitlib-3.0.10/arpakitlib/common_util/really_validate_email.py +1 -21
- arpakitlib-3.0.2/arpakitlib/common_/ar_retry_func_util.py → arpakitlib-3.0.10/arpakitlib/common_util/retry_func.py +3 -58
- arpakitlib-3.0.2/arpakitlib/common_/ar_str_etc_util.py → arpakitlib-3.0.10/arpakitlib/common_util/str_etc.py +2 -0
- arpakitlib-3.0.10/arpakitlib/http_client_util/__init__.py +0 -0
- arpakitlib-3.0.10/arpakitlib/http_client_util/base_http_client.py +54 -0
- arpakitlib-3.0.10/arpakitlib/http_client_util/http_request.py +304 -0
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_pydantic_schema_from_sqlalchemy_model_util.py → arpakitlib-3.0.10/arpakitlib/sqlalchemy_util/pydantic_schema_from_sqlalchemy_model.py +3 -85
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_base_dbm_util.py → arpakitlib-3.0.10/arpakitlib/sqlalchemy_util/sqlalchemy_base_dbm.py +1 -64
- arpakitlib-3.0.10/arpakitlib/sqlalchemy_util/sqlalchemy_db.py +555 -0
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_declarative_base_info_util.py → arpakitlib-3.0.10/arpakitlib/sqlalchemy_util/sqlalchemy_declarative_base_info.py +4 -29
- arpakitlib-3.0.10/arpakitlib/zip_util/__init__.py +0 -0
- arpakitlib-3.0.10/arpakitlib/zip_util/make_zip_archive.py +168 -0
- {arpakitlib-3.0.2 → arpakitlib-3.0.10}/pyproject.toml +26 -19
- arpakitlib-3.0.2/README.md +0 -116
- arpakitlib-3.0.2/arpakitlib/aiogram_/ar_aiogram_as_tg_command_util.py +0 -190
- arpakitlib-3.0.2/arpakitlib/aiogram_/ar_include_aiogram_routers_from_dir_util.py +0 -34
- arpakitlib-3.0.2/arpakitlib/common_/ar_generate_connection_url_util.py +0 -108
- arpakitlib-3.0.2/arpakitlib/common_/ar_generate_difficult_password_util.py +0 -83
- arpakitlib-3.0.2/arpakitlib/common_/ar_generate_simple_code_util.py +0 -57
- arpakitlib-3.0.2/arpakitlib/common_/ar_json_util.py +0 -142
- arpakitlib-3.0.2/arpakitlib/etc_/ar_make_zip_with_passwd_util.py +0 -154
- arpakitlib-3.0.2/arpakitlib/fastapi_/__init__.py +0 -1
- arpakitlib-3.0.2/arpakitlib/fastapi_/ar_include_fastapi_routers_from_dir_util.py +0 -37
- arpakitlib-3.0.2/arpakitlib/http_client_/__init__.py +0 -1
- arpakitlib-3.0.2/arpakitlib/http_client_/ar_base_http_api_client_util.py +0 -65
- arpakitlib-3.0.2/arpakitlib/http_client_/ar_http_request_util.py +0 -279
- arpakitlib-3.0.2/arpakitlib/pydantic_/__init__.py +0 -1
- arpakitlib-3.0.2/arpakitlib/sqladmin_/__init__.py +0 -1
- arpakitlib-3.0.2/arpakitlib/sqladmin_/ar_sqladmin_etc_util.py +0 -94
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/__init__.py +0 -1
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_db_util.py +0 -243
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_drop_check_constraints_util.py +0 -101
- arpakitlib-3.0.2/arpakitlib/sqlalchemy_/ar_sqlalchemy_ensure_check_constraints_util.py +0 -138
- {arpakitlib-3.0.2 → arpakitlib-3.0.10}/arpakitlib/__init__.py +0 -0
- {arpakitlib-3.0.2/arpakitlib/aiogram_ → arpakitlib-3.0.10/arpakitlib/aiogram_util}/__init__.py +0 -0
- {arpakitlib-3.0.2/arpakitlib/common_ → arpakitlib-3.0.10/arpakitlib/common_util}/__init__.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_enumeration_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/enumeration.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_exception_etc_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/exception_etc.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_ip_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/ip_etc.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_run_cmd_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/run_cmd.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_safe_sleep_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/safe_sleep.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_simple_settings_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/simple_settings.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_type_etc_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/type_etc.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_typed_objects_from_dir_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/typed_objects_from_dir.py +0 -0
- /arpakitlib-3.0.2/arpakitlib/common_/ar_uuid_etc_util.py → /arpakitlib-3.0.10/arpakitlib/common_util/uuid_etc.py +0 -0
- {arpakitlib-3.0.2/arpakitlib/etc_ → arpakitlib-3.0.10/arpakitlib/sqlalchemy_util}/__init__.py +0 -0
|
@@ -186,7 +186,7 @@
|
|
|
186
186
|
same "printed page" as the copyright notice for easier
|
|
187
187
|
identification within third-party archives.
|
|
188
188
|
|
|
189
|
-
Copyright 2024-present
|
|
189
|
+
Copyright 2024-present arpakit
|
|
190
190
|
|
|
191
191
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
192
|
you may not use this file except in compliance with the License.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: arpakitlib
|
|
3
|
-
Version: 3.0.
|
|
4
|
-
Summary: Lightweight and convenient development tools by
|
|
3
|
+
Version: 3.0.10
|
|
4
|
+
Summary: Lightweight and convenient development tools by arpakit
|
|
5
5
|
License-Expression: Apache-2.0
|
|
6
6
|
License-File: LICENSE
|
|
7
7
|
Keywords: arpakitlib,arpakit,arpakit-company,arpakitcompany,arpakit_company
|
|
8
|
-
Author:
|
|
9
|
-
Author-email:
|
|
10
|
-
Requires-Python: >=3.13.4,<
|
|
8
|
+
Author: arpakit
|
|
9
|
+
Author-email: arpakit@gmail.com
|
|
10
|
+
Requires-Python: >=3.13.4,<4
|
|
11
11
|
Classifier: Development Status :: 5 - Production/Stable
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
13
|
Classifier: Programming Language :: Python
|
|
@@ -18,20 +18,20 @@ Classifier: Operating System :: OS Independent
|
|
|
18
18
|
Classifier: Topic :: Software Development :: Libraries
|
|
19
19
|
Classifier: Topic :: Utilities
|
|
20
20
|
Classifier: Framework :: AsyncIO
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
Provides-Extra: aiogram-util
|
|
22
|
+
Provides-Extra: http-client-util
|
|
23
|
+
Provides-Extra: sqlalchemy-util
|
|
24
|
+
Provides-Extra: zip-util
|
|
25
|
+
Requires-Dist: aiogram (>=3.31.0,<4.0.0) ; (python_version < "3.15") and (extra == "aiogram-util")
|
|
26
|
+
Requires-Dist: asyncpg (>=0.31.0,<0.32.0) ; extra == "sqlalchemy-util"
|
|
25
27
|
Requires-Dist: email-validator (>=2.2.0,<3.0.0)
|
|
26
|
-
Requires-Dist:
|
|
28
|
+
Requires-Dist: httpx[http2,socks] (>=0.28.1,<0.29.0) ; extra == "http-client-util"
|
|
27
29
|
Requires-Dist: orjson (>=3.12.0,<4.0.0)
|
|
28
|
-
Requires-Dist: psycopg2-binary (>=2.9.
|
|
30
|
+
Requires-Dist: psycopg2-binary (>=2.9.13,<3.0.0) ; extra == "sqlalchemy-util"
|
|
29
31
|
Requires-Dist: pydantic (>=2.13.5,<3.0.0)
|
|
30
32
|
Requires-Dist: pydantic-settings (>=2.7.1,<3.0.0)
|
|
31
|
-
Requires-Dist:
|
|
32
|
-
Requires-Dist:
|
|
33
|
-
Requires-Dist: sqladmin (>=0.31.1,<0.32.0)
|
|
34
|
-
Requires-Dist: sqlalchemy (>=2.0.52,<3.0.0)
|
|
33
|
+
Requires-Dist: pyzipper (>=0.4.0,<0.5.0) ; extra == "zip-util"
|
|
34
|
+
Requires-Dist: sqlalchemy (>=2.0.53,<3.0.0) ; extra == "sqlalchemy-util"
|
|
35
35
|
Project-URL: ARPAKIT Company, https://arpakit.com
|
|
36
36
|
Project-URL: Documentation, https://github.com/ARPAKIT-Company/arpakitlib
|
|
37
37
|
Project-URL: Homepage, https://github.com/ARPAKIT-Company/arpakitlib
|
|
@@ -45,7 +45,7 @@ Description-Content-Type: text/markdown
|
|
|
45
45
|
|
|
46
46
|
## 🚀 Simplify Your Development Workflow
|
|
47
47
|
|
|
48
|
-
A collection of lightweight and convenient development tools by
|
|
48
|
+
A collection of lightweight and convenient development tools by arpakit, designed to simplify and accelerate
|
|
49
49
|
your workflow.
|
|
50
50
|
|
|
51
51
|
[](https://pypi.org/project/arpakitlib/)
|
|
@@ -56,23 +56,31 @@ your workflow.
|
|
|
56
56
|
|
|
57
57
|
### What is inside
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
A set of small, self-contained utilities you pick from one at a time.
|
|
60
60
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
+
The base install stays light and pulls only a handful of packages. Everything that needs a heavier library lives in
|
|
62
|
+
its own subpackage behind an optional extra, so you install a web framework or a bot framework only if you actually
|
|
63
|
+
use that part.
|
|
71
64
|
|
|
72
|
-
|
|
65
|
+
| Subpackage | Extra | What is inside |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `common_util` | always installed | JSON, dates, strings, dictionaries, files, settings, background workers, retries, enumerations, shell commands, database dumps, email validation |
|
|
68
|
+
| `http_client_util` | `http-client-util` | sync and async requests with retries and proxy support, plus a base API client |
|
|
69
|
+
| `sqlalchemy_util` | `sqlalchemy-util` | declarative base with introspection, database helper, check constraints, pydantic schemas from existing models |
|
|
70
|
+
| `sqladmin_util` | `sqladmin-util` | introspection for admin model views |
|
|
71
|
+
| `aiogram_util` | `aiogram-util` | parsing telegram bot commands |
|
|
72
|
+
|
|
73
|
+
Every module keeps its own runnable example, so the fastest way to see what a utility does is to run that
|
|
74
|
+
module directly:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python -m arpakitlib.<subpackage>.<module>
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
For example:
|
|
73
81
|
|
|
74
82
|
```bash
|
|
75
|
-
python -m arpakitlib.
|
|
83
|
+
python -m arpakitlib.common_util.json
|
|
76
84
|
```
|
|
77
85
|
|
|
78
86
|
---
|
|
@@ -85,6 +93,8 @@ python -m arpakitlib.common_.ar_json_util
|
|
|
85
93
|
|
|
86
94
|
### Installation
|
|
87
95
|
|
|
96
|
+
The base install gives you everything in `common_util`:
|
|
97
|
+
|
|
88
98
|
```bash
|
|
89
99
|
pip install arpakitlib
|
|
90
100
|
```
|
|
@@ -97,10 +107,24 @@ poetry add arpakitlib
|
|
|
97
107
|
uv add arpakitlib
|
|
98
108
|
```
|
|
99
109
|
|
|
110
|
+
Add the extras you need, separately or several at once:
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
pip install "arpakitlib[sqlalchemy-util]"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
pip install "arpakitlib[aiogram-util,http-client-util]"
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
poetry add "arpakitlib[sqlalchemy-util,sqladmin-util]"
|
|
122
|
+
```
|
|
123
|
+
|
|
100
124
|
Pin an exact version:
|
|
101
125
|
|
|
102
126
|
```bash
|
|
103
|
-
pip install arpakitlib==
|
|
127
|
+
pip install arpakitlib==3.0.5
|
|
104
128
|
```
|
|
105
129
|
|
|
106
130
|
Install straight from the repository:
|
|
@@ -123,15 +147,15 @@ pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://
|
|
|
123
147
|
from datetime import datetime
|
|
124
148
|
from decimal import Decimal
|
|
125
149
|
|
|
126
|
-
from arpakitlib.
|
|
150
|
+
from arpakitlib.common_util.json_etc import convert_data_to_json_str
|
|
127
151
|
|
|
128
|
-
print(
|
|
152
|
+
print(convert_data_to_json_str({"when": datetime(2026, 9, 4), "price": Decimal("1.5")}))
|
|
129
153
|
# {
|
|
130
154
|
# "when": "2026-09-04T00:00:00",
|
|
131
155
|
# "price": "1.5"
|
|
132
156
|
# }
|
|
133
157
|
|
|
134
|
-
print(
|
|
158
|
+
print(convert_data_to_json_str({"when": datetime(2026, 9, 4)}, beautify=False))
|
|
135
159
|
# {"when":"2026-09-04T00:00:00"}
|
|
136
160
|
```
|
|
137
161
|
|
|
@@ -139,9 +163,16 @@ print(transfer_data_to_json_str({"when": datetime(2026, 9, 4)}, beautify=False))
|
|
|
139
163
|
|
|
140
164
|
### Development
|
|
141
165
|
|
|
166
|
+
Extras are not installed by default, so use `--all-extras` to get a full environment:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
poetry install --all-extras
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Then run any module's example to check things work:
|
|
173
|
+
|
|
142
174
|
```bash
|
|
143
|
-
|
|
144
|
-
poetry run pytest
|
|
175
|
+
python -m arpakitlib.common_util.json
|
|
145
176
|
```
|
|
146
177
|
|
|
147
178
|
---
|
|
@@ -156,5 +187,5 @@ poetry run pytest
|
|
|
156
187
|
|
|
157
188
|
---
|
|
158
189
|
|
|
159
|
-
## ❤️ Made by
|
|
190
|
+
## ❤️ Made by arpakit ❤️
|
|
160
191
|
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# arpakitlib
|
|
2
|
+
|
|
3
|
+
## 🚀 Simplify Your Development Workflow
|
|
4
|
+
|
|
5
|
+
A collection of lightweight and convenient development tools by arpakit, designed to simplify and accelerate
|
|
6
|
+
your workflow.
|
|
7
|
+
|
|
8
|
+
[](https://pypi.org/project/arpakitlib/)
|
|
9
|
+
[](https://pypi.org/project/arpakitlib/)
|
|
10
|
+
[](https://github.com/ARPAKIT-Company/arpakitlib/blob/master/LICENSE)
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
### What is inside
|
|
15
|
+
|
|
16
|
+
A set of small, self-contained utilities you pick from one at a time.
|
|
17
|
+
|
|
18
|
+
The base install stays light and pulls only a handful of packages. Everything that needs a heavier library lives in
|
|
19
|
+
its own subpackage behind an optional extra, so you install a web framework or a bot framework only if you actually
|
|
20
|
+
use that part.
|
|
21
|
+
|
|
22
|
+
| Subpackage | Extra | What is inside |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| `common_util` | always installed | JSON, dates, strings, dictionaries, files, settings, background workers, retries, enumerations, shell commands, database dumps, email validation |
|
|
25
|
+
| `http_client_util` | `http-client-util` | sync and async requests with retries and proxy support, plus a base API client |
|
|
26
|
+
| `sqlalchemy_util` | `sqlalchemy-util` | declarative base with introspection, database helper, check constraints, pydantic schemas from existing models |
|
|
27
|
+
| `sqladmin_util` | `sqladmin-util` | introspection for admin model views |
|
|
28
|
+
| `aiogram_util` | `aiogram-util` | parsing telegram bot commands |
|
|
29
|
+
|
|
30
|
+
Every module keeps its own runnable example, so the fastest way to see what a utility does is to run that
|
|
31
|
+
module directly:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
python -m arpakitlib.<subpackage>.<module>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
For example:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
python -m arpakitlib.common_util.json
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
### Supported Python version
|
|
46
|
+
|
|
47
|
+
- Python 3.13.4 and above
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
### Installation
|
|
52
|
+
|
|
53
|
+
The base install gives you everything in `common_util`:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install arpakitlib
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
poetry add arpakitlib
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
uv add arpakitlib
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Add the extras you need, separately or several at once:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install "arpakitlib[sqlalchemy-util]"
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install "arpakitlib[aiogram-util,http-client-util]"
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
poetry add "arpakitlib[sqlalchemy-util,sqladmin-util]"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Pin an exact version:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install arpakitlib==3.0.5
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Install straight from the repository:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
pip install git+https://github.com/ARPAKIT-Company/arpakitlib.git
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Install a pre-release from TestPyPI:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ arpakitlib
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
### Quick start
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from datetime import datetime
|
|
105
|
+
from decimal import Decimal
|
|
106
|
+
|
|
107
|
+
from arpakitlib.common_util.json_etc import convert_data_to_json_str
|
|
108
|
+
|
|
109
|
+
print(convert_data_to_json_str({"when": datetime(2026, 9, 4), "price": Decimal("1.5")}))
|
|
110
|
+
# {
|
|
111
|
+
# "when": "2026-09-04T00:00:00",
|
|
112
|
+
# "price": "1.5"
|
|
113
|
+
# }
|
|
114
|
+
|
|
115
|
+
print(convert_data_to_json_str({"when": datetime(2026, 9, 4)}, beautify=False))
|
|
116
|
+
# {"when":"2026-09-04T00:00:00"}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
### Development
|
|
122
|
+
|
|
123
|
+
Extras are not installed by default, so use `--all-extras` to get a full environment:
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
poetry install --all-extras
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Then run any module's example to check things work:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
python -m arpakitlib.common_util.json
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
### Links
|
|
138
|
+
|
|
139
|
+
- [GitHub](https://github.com/ARPAKIT-Company/arpakitlib)
|
|
140
|
+
- [PyPI](https://pypi.org/project/arpakitlib/)
|
|
141
|
+
- [Telegram channel](https://t.me/arpakitlib)
|
|
142
|
+
- [ARPAKIT Company](https://arpakit.com)
|
|
143
|
+
- [Support](https://t.me/arpakit_company_support)
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## ❤️ Made by arpakit ❤️
|
|
@@ -0,0 +1,257 @@
|
|
|
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_util.parse_command 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
|
+
pass
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
async def __async_example():
|
|
252
|
+
pass
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
if __name__ == '__main__':
|
|
256
|
+
__example()
|
|
257
|
+
asyncio.run(__async_example())
|