chutils 2.4.0__tar.gz → 2.6.0__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.
- {chutils-2.4.0 → chutils-2.6.0}/LICENSE +1 -1
- chutils-2.6.0/PKG-INFO +299 -0
- chutils-2.6.0/README.md +267 -0
- chutils-2.6.0/pyproject.toml +70 -0
- {chutils-2.4.0 → chutils-2.6.0}/src/chutils/__init__.py +24 -11
- chutils-2.6.0/src/chutils/cli.py +71 -0
- chutils-2.6.0/src/chutils/config/__init__.py +602 -0
- chutils-2.6.0/src/chutils/config/manager.py +98 -0
- chutils-2.6.0/src/chutils/config/providers.py +234 -0
- chutils-2.6.0/src/chutils/config/utils.py +123 -0
- chutils-2.6.0/src/chutils/config/watcher.py +137 -0
- chutils-2.6.0/src/chutils/context.py +60 -0
- chutils-2.6.0/src/chutils/decorators.py +198 -0
- {chutils-2.4.0 → chutils-2.6.0}/src/chutils/logger.py +249 -81
- {chutils-2.4.0 → chutils-2.6.0}/src/chutils/secret_manager.py +109 -61
- chutils-2.4.0/PKG-INFO +0 -418
- chutils-2.4.0/README.md +0 -396
- chutils-2.4.0/pyproject.toml +0 -52
- chutils-2.4.0/src/chutils/config.py +0 -634
- chutils-2.4.0/src/chutils/decorators.py +0 -55
chutils-2.6.0/PKG-INFO
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: chutils
|
|
3
|
+
Version: 2.6.0
|
|
4
|
+
Summary: Набор простых и удобных утилит для Python, который избавляет от рутины при работе с конфигурацией и логированием в новых проектах.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Chu4hel
|
|
8
|
+
Author-email: sergeiivanov636@gmail.com
|
|
9
|
+
Requires-Python: >=3.9, !=3.9.0, !=3.9.1
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Provides-Extra: full
|
|
17
|
+
Provides-Extra: json
|
|
18
|
+
Provides-Extra: pydantic
|
|
19
|
+
Provides-Extra: watch
|
|
20
|
+
Requires-Dist: keyring (>=25.7.0)
|
|
21
|
+
Requires-Dist: pydantic (>=2.13.4) ; extra == "full"
|
|
22
|
+
Requires-Dist: pydantic (>=2.13.4,<3.0.0) ; extra == "pydantic"
|
|
23
|
+
Requires-Dist: python-dotenv (>=1.2.1) ; python_full_version < "3.10.0"
|
|
24
|
+
Requires-Dist: python-dotenv (>=1.2.2) ; python_full_version >= "3.10.0"
|
|
25
|
+
Requires-Dist: python-json-logger (>=3.2.1) ; extra == "full"
|
|
26
|
+
Requires-Dist: python-json-logger (>=3.2.1) ; extra == "json"
|
|
27
|
+
Requires-Dist: pyyaml (>=6.0.3)
|
|
28
|
+
Requires-Dist: watchdog (>=6.0.0) ; extra == "full"
|
|
29
|
+
Requires-Dist: watchdog (>=6.0.0) ; extra == "watch"
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
[Русская версия](docs/README_RU.md)
|
|
33
|
+
|
|
34
|
+
# chutils: Stop the Routine!
|
|
35
|
+
|
|
36
|
+
[](https://opensource.org/licenses/MIT)
|
|
37
|
+
[](https://www.python.org/downloads/)
|
|
38
|
+
[](https://badge.fury.io/py/chutils)
|
|
39
|
+
[](https://Chu4hel.github.io/chutils/)
|
|
40
|
+
|
|
41
|
+
**chutils** is a set of simple utilities for Python designed to eliminate the repetitive setup of configuration,
|
|
42
|
+
logging, and secrets in your projects.
|
|
43
|
+
|
|
44
|
+
Start a new project and focus on what matters, not the routine.
|
|
45
|
+
|
|
46
|
+
Full documentation is available on [our website](https://Chu4hel.github.io/chutils/) (currently in Russian).
|
|
47
|
+
|
|
48
|
+
## The Problem
|
|
49
|
+
|
|
50
|
+
Every time you start a new project, you have to solve the same tasks:
|
|
51
|
+
|
|
52
|
+
- How to conveniently read settings from a configuration file?
|
|
53
|
+
- How to configure logging to write messages to both the console and a file with daily rotation?
|
|
54
|
+
- How to securely store API keys without hardcoding them in the code?
|
|
55
|
+
- How to make it all work "out of the box" without manually defining paths?
|
|
56
|
+
|
|
57
|
+
**chutils** offers ready-made solutions for all these problems.
|
|
58
|
+
|
|
59
|
+
## Key Features
|
|
60
|
+
|
|
61
|
+
- **✨ Zero Configuration:** The library **automatically** finds your project root and the `config.yml` or `config.ini`
|
|
62
|
+
file. It uses **lazy initialization** — no heavy operations until you actually need them.
|
|
63
|
+
- **⚙️ Flexible Configuration:** Support for `YAML` and `INI` formats. Simple functions for retrieving typed data.
|
|
64
|
+
- **✍️ Advanced Logger:** The `setup_logger()` function configures logging to the console and rotating files out of the
|
|
65
|
+
box. It returns a custom logger with additional debug levels (`devdebug`, `mediumdebug`).
|
|
66
|
+
- **🔒 Secure Secret Storage:** The `secret_manager` module provides a simple interface for saving and retrieving secrets
|
|
67
|
+
via the system `keyring`, with a fallback to `.env` files.
|
|
68
|
+
- **🔄 Hot-Reload:** Support for automatic configuration reloading on file changes without restart (requires
|
|
69
|
+
`pip install chutils[watch]`).
|
|
70
|
+
- **⚡ Async Ready:** Most core functions have asynchronous versions (prefixed with `a`) for non-blocking execution.
|
|
71
|
+
- **🚀 Ready to Use:** Just install and use.
|
|
72
|
+
|
|
73
|
+
## Command Line Interface (CLI)
|
|
74
|
+
|
|
75
|
+
The library provides a `chutils` console command for convenient secret management without writing code.
|
|
76
|
+
|
|
77
|
+
### Secret Management
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# Save a secret to the system storage (keyring)
|
|
81
|
+
chutils secrets set MY_API_KEY "super-secret-value"
|
|
82
|
+
|
|
83
|
+
# Delete a secret
|
|
84
|
+
chutils secrets delete MY_API_KEY
|
|
85
|
+
|
|
86
|
+
# Explicitly specify service name
|
|
87
|
+
chutils secrets set DB_PASSWORD "12345" --service my_custom_app
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Installation
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
poetry add chutils
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or using pip:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
pip install chutils
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Examples
|
|
103
|
+
|
|
104
|
+
In the [`/examples`](./examples/) folder, you will find ready-to-run scripts demonstrating the library's key features.
|
|
105
|
+
Each example focuses on a specific task.
|
|
106
|
+
|
|
107
|
+
## Quick Start
|
|
108
|
+
|
|
109
|
+
### 1. Working with Configuration
|
|
110
|
+
|
|
111
|
+
1. (Optional) Create a `config.yml` file in your project root:
|
|
112
|
+
|
|
113
|
+
```yaml
|
|
114
|
+
# config.yml
|
|
115
|
+
Database:
|
|
116
|
+
host: localhost
|
|
117
|
+
port: 5432
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
2. Get values in your code:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from chutils import get_config_value, get_config_int
|
|
124
|
+
|
|
125
|
+
db_host = get_config_value("Database", "host", fallback="127.0.0.1")
|
|
126
|
+
db_port = get_config_int("Database", "port", fallback=5432)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
#### Validation via Pydantic (Optional)
|
|
130
|
+
|
|
131
|
+
For strict typing and validation, you can use Pydantic models (requires `pip install chutils[pydantic]`):
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from pydantic import BaseModel
|
|
135
|
+
from chutils import get_config
|
|
136
|
+
|
|
137
|
+
class AppConfig(BaseModel):
|
|
138
|
+
app_name: str
|
|
139
|
+
version: str
|
|
140
|
+
|
|
141
|
+
# Returns an instance of AppConfig
|
|
142
|
+
cfg = get_config(model=AppConfig)
|
|
143
|
+
print(cfg.app_name)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
You can also validate specific sections:
|
|
147
|
+
```python
|
|
148
|
+
from chutils import get_config_section
|
|
149
|
+
db_cfg = get_config_section("Database", model=MyDbModel)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
#### Overriding Configuration with Local Files (`config.local.yml`)
|
|
153
|
+
|
|
154
|
+
You can create a `config.local.yml` next to your main file. Values from the local file will **override**
|
|
155
|
+
corresponding values from the main file. This is perfect for local development or storing sensitive data (ensure
|
|
156
|
+
`*.local.*` is in your `.gitignore`).
|
|
157
|
+
|
|
158
|
+
### 2. Hot-Reload
|
|
159
|
+
|
|
160
|
+
You can make your application react to configuration file changes in real-time.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from chutils import start_config_watcher, on_config_change, get_config_value
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def reload_logic():
|
|
167
|
+
print("Configuration updated!")
|
|
168
|
+
# Update app state here
|
|
169
|
+
db_url = get_config_value("Database", "url")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# Register callback
|
|
173
|
+
on_config_change(reload_logic)
|
|
174
|
+
|
|
175
|
+
# Start watcher (requires watchdog package)
|
|
176
|
+
start_config_watcher()
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
To use this feature, install `watchdog`:
|
|
180
|
+
`pip install chutils[watch]`
|
|
181
|
+
|
|
182
|
+
### 3. Logging Setup
|
|
183
|
+
|
|
184
|
+
1. Configure and use the logger:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
from chutils import setup_logger, ChutilsLogger
|
|
188
|
+
|
|
189
|
+
# Automatically reads settings from [Logging] section in config.yml
|
|
190
|
+
logger: ChutilsLogger = setup_logger()
|
|
191
|
+
|
|
192
|
+
logger.info("Application started.")
|
|
193
|
+
logger.devdebug("Deep debug message (level 9).")
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
#### Structured Logging (JSON)
|
|
197
|
+
|
|
198
|
+
If you need to output logs in JSON format for ELK, Splunk, or cloud logging (requires `pip install chutils[json]`):
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
# Via code
|
|
202
|
+
logger = setup_logger(json_format=True)
|
|
203
|
+
|
|
204
|
+
# Or via config in the [Logging] section
|
|
205
|
+
# json_format: true
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
#### Contextual Logging (ContextVar)
|
|
209
|
+
|
|
210
|
+
You can bind metadata to the current execution context (thread or coroutine), and it will be automatically
|
|
211
|
+
included in all log messages.
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
from chutils import setup_logger, bind_context
|
|
215
|
+
|
|
216
|
+
logger = setup_logger()
|
|
217
|
+
|
|
218
|
+
# Bind request ID and user to the current context
|
|
219
|
+
bind_context(request_id="REQ-123", user="admin")
|
|
220
|
+
|
|
221
|
+
logger.info("Action performed")
|
|
222
|
+
# Text: ... [request_id=REQ-123 user=admin] Action performed
|
|
223
|
+
# JSON: {..., "message": "Action performed", "context": {"request_id": "REQ-123", "user": "admin"}}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
#### Controlling Logging via Environment Variables
|
|
227
|
+
|
|
228
|
+
- `CH_LOG_JSON=true`: Forces JSON format.
|
|
229
|
+
- `CH_LOG_NO_TIME=true`: Removes the date/time from the log format (for clean Docker logs).
|
|
230
|
+
- `CH_LOG_NO_FILE=true`: Disables creating log files.
|
|
231
|
+
|
|
232
|
+
These variables have **highest priority** and override any code or config settings.
|
|
233
|
+
|
|
234
|
+
### 3. Secret Management
|
|
235
|
+
|
|
236
|
+
`SecretManager` looks for secrets in the following order: **Keyring > .env File > Environment Variables**.
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
from chutils import SecretManager
|
|
240
|
+
|
|
241
|
+
secrets = SecretManager("my_awesome_app")
|
|
242
|
+
|
|
243
|
+
# Save once
|
|
244
|
+
secrets.save_secret("API_KEY", "secret-value-123")
|
|
245
|
+
|
|
246
|
+
# Use everywhere
|
|
247
|
+
key = secrets.get_secret("API_KEY")
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
#### Disabling Keyring (Optional)
|
|
251
|
+
|
|
252
|
+
In environments like Docker or CI/CD where `keyring` is unavailable, you can suppress warnings and skip the check:
|
|
253
|
+
|
|
254
|
+
- Set `CH_DISABLE_KEYRING_WARNING=true` in environment.
|
|
255
|
+
- Or add `disable_keyring: true` under `secrets` section in `config.yml`.
|
|
256
|
+
|
|
257
|
+
## API Overview
|
|
258
|
+
|
|
259
|
+
### Configuration (`chutils.config`)
|
|
260
|
+
|
|
261
|
+
- `get_config_value(section, key, fallback)` / `aget_config()`
|
|
262
|
+
- `get_config_int`, `get_config_boolean`, `get_config_list`, `get_config_path`
|
|
263
|
+
- `save_config_value(section, key, value, notify=True)` / `asave_config_value()`
|
|
264
|
+
- Use `notify=False` to update the file without triggering Hot-Reload callbacks.
|
|
265
|
+
|
|
266
|
+
### Logging (`chutils.logger`)
|
|
267
|
+
|
|
268
|
+
- `setup_logger(name, log_level, log_file_name, rotation_type, compress, ...)`
|
|
269
|
+
- Levels: `logger.devdebug` (9), `logger.mediumdebug` (15), and all standard ones.
|
|
270
|
+
|
|
271
|
+
### Secret Management (`chutils.secret_manager`)
|
|
272
|
+
|
|
273
|
+
- `SecretManager(service_name, prefix)`
|
|
274
|
+
- `save_secret` / `asave_secret`
|
|
275
|
+
- `get_secret` / `aget_secret`
|
|
276
|
+
- `delete_secret` / `adelete_secret`
|
|
277
|
+
|
|
278
|
+
### Decorators (`chutils.decorators`)
|
|
279
|
+
|
|
280
|
+
- `@log_function_details`: Logs arguments, execution time, and result (uses `DEVDEBUG` level).
|
|
281
|
+
- `@timeout(seconds, fallback)`: Limits function execution time. Supports sync/async and optional fallback.
|
|
282
|
+
- `@retry`: Automatically retries a function if it fails. Supports sync/async, backoff, jitter, and exception filtering.
|
|
283
|
+
|
|
284
|
+
#### Example of @retry usage:
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
from chutils.decorators import retry
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@retry(retries=3, delay=1.0, backoff=2.0)
|
|
291
|
+
def fetch_data():
|
|
292
|
+
# Will be retried up to 3 times on any Exception
|
|
293
|
+
...
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
## License
|
|
297
|
+
|
|
298
|
+
The project is distributed under the MIT License.
|
|
299
|
+
|
chutils-2.6.0/README.md
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
[Русская версия](docs/README_RU.md)
|
|
2
|
+
|
|
3
|
+
# chutils: Stop the Routine!
|
|
4
|
+
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
[](https://www.python.org/downloads/)
|
|
7
|
+
[](https://badge.fury.io/py/chutils)
|
|
8
|
+
[](https://Chu4hel.github.io/chutils/)
|
|
9
|
+
|
|
10
|
+
**chutils** is a set of simple utilities for Python designed to eliminate the repetitive setup of configuration,
|
|
11
|
+
logging, and secrets in your projects.
|
|
12
|
+
|
|
13
|
+
Start a new project and focus on what matters, not the routine.
|
|
14
|
+
|
|
15
|
+
Full documentation is available on [our website](https://Chu4hel.github.io/chutils/) (currently in Russian).
|
|
16
|
+
|
|
17
|
+
## The Problem
|
|
18
|
+
|
|
19
|
+
Every time you start a new project, you have to solve the same tasks:
|
|
20
|
+
|
|
21
|
+
- How to conveniently read settings from a configuration file?
|
|
22
|
+
- How to configure logging to write messages to both the console and a file with daily rotation?
|
|
23
|
+
- How to securely store API keys without hardcoding them in the code?
|
|
24
|
+
- How to make it all work "out of the box" without manually defining paths?
|
|
25
|
+
|
|
26
|
+
**chutils** offers ready-made solutions for all these problems.
|
|
27
|
+
|
|
28
|
+
## Key Features
|
|
29
|
+
|
|
30
|
+
- **✨ Zero Configuration:** The library **automatically** finds your project root and the `config.yml` or `config.ini`
|
|
31
|
+
file. It uses **lazy initialization** — no heavy operations until you actually need them.
|
|
32
|
+
- **⚙️ Flexible Configuration:** Support for `YAML` and `INI` formats. Simple functions for retrieving typed data.
|
|
33
|
+
- **✍️ Advanced Logger:** The `setup_logger()` function configures logging to the console and rotating files out of the
|
|
34
|
+
box. It returns a custom logger with additional debug levels (`devdebug`, `mediumdebug`).
|
|
35
|
+
- **🔒 Secure Secret Storage:** The `secret_manager` module provides a simple interface for saving and retrieving secrets
|
|
36
|
+
via the system `keyring`, with a fallback to `.env` files.
|
|
37
|
+
- **🔄 Hot-Reload:** Support for automatic configuration reloading on file changes without restart (requires
|
|
38
|
+
`pip install chutils[watch]`).
|
|
39
|
+
- **⚡ Async Ready:** Most core functions have asynchronous versions (prefixed with `a`) for non-blocking execution.
|
|
40
|
+
- **🚀 Ready to Use:** Just install and use.
|
|
41
|
+
|
|
42
|
+
## Command Line Interface (CLI)
|
|
43
|
+
|
|
44
|
+
The library provides a `chutils` console command for convenient secret management without writing code.
|
|
45
|
+
|
|
46
|
+
### Secret Management
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
# Save a secret to the system storage (keyring)
|
|
50
|
+
chutils secrets set MY_API_KEY "super-secret-value"
|
|
51
|
+
|
|
52
|
+
# Delete a secret
|
|
53
|
+
chutils secrets delete MY_API_KEY
|
|
54
|
+
|
|
55
|
+
# Explicitly specify service name
|
|
56
|
+
chutils secrets set DB_PASSWORD "12345" --service my_custom_app
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Installation
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
poetry add chutils
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Or using pip:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install chutils
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Examples
|
|
72
|
+
|
|
73
|
+
In the [`/examples`](./examples/) folder, you will find ready-to-run scripts demonstrating the library's key features.
|
|
74
|
+
Each example focuses on a specific task.
|
|
75
|
+
|
|
76
|
+
## Quick Start
|
|
77
|
+
|
|
78
|
+
### 1. Working with Configuration
|
|
79
|
+
|
|
80
|
+
1. (Optional) Create a `config.yml` file in your project root:
|
|
81
|
+
|
|
82
|
+
```yaml
|
|
83
|
+
# config.yml
|
|
84
|
+
Database:
|
|
85
|
+
host: localhost
|
|
86
|
+
port: 5432
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
2. Get values in your code:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from chutils import get_config_value, get_config_int
|
|
93
|
+
|
|
94
|
+
db_host = get_config_value("Database", "host", fallback="127.0.0.1")
|
|
95
|
+
db_port = get_config_int("Database", "port", fallback=5432)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### Validation via Pydantic (Optional)
|
|
99
|
+
|
|
100
|
+
For strict typing and validation, you can use Pydantic models (requires `pip install chutils[pydantic]`):
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from pydantic import BaseModel
|
|
104
|
+
from chutils import get_config
|
|
105
|
+
|
|
106
|
+
class AppConfig(BaseModel):
|
|
107
|
+
app_name: str
|
|
108
|
+
version: str
|
|
109
|
+
|
|
110
|
+
# Returns an instance of AppConfig
|
|
111
|
+
cfg = get_config(model=AppConfig)
|
|
112
|
+
print(cfg.app_name)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
You can also validate specific sections:
|
|
116
|
+
```python
|
|
117
|
+
from chutils import get_config_section
|
|
118
|
+
db_cfg = get_config_section("Database", model=MyDbModel)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
#### Overriding Configuration with Local Files (`config.local.yml`)
|
|
122
|
+
|
|
123
|
+
You can create a `config.local.yml` next to your main file. Values from the local file will **override**
|
|
124
|
+
corresponding values from the main file. This is perfect for local development or storing sensitive data (ensure
|
|
125
|
+
`*.local.*` is in your `.gitignore`).
|
|
126
|
+
|
|
127
|
+
### 2. Hot-Reload
|
|
128
|
+
|
|
129
|
+
You can make your application react to configuration file changes in real-time.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from chutils import start_config_watcher, on_config_change, get_config_value
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def reload_logic():
|
|
136
|
+
print("Configuration updated!")
|
|
137
|
+
# Update app state here
|
|
138
|
+
db_url = get_config_value("Database", "url")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# Register callback
|
|
142
|
+
on_config_change(reload_logic)
|
|
143
|
+
|
|
144
|
+
# Start watcher (requires watchdog package)
|
|
145
|
+
start_config_watcher()
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
To use this feature, install `watchdog`:
|
|
149
|
+
`pip install chutils[watch]`
|
|
150
|
+
|
|
151
|
+
### 3. Logging Setup
|
|
152
|
+
|
|
153
|
+
1. Configure and use the logger:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from chutils import setup_logger, ChutilsLogger
|
|
157
|
+
|
|
158
|
+
# Automatically reads settings from [Logging] section in config.yml
|
|
159
|
+
logger: ChutilsLogger = setup_logger()
|
|
160
|
+
|
|
161
|
+
logger.info("Application started.")
|
|
162
|
+
logger.devdebug("Deep debug message (level 9).")
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Structured Logging (JSON)
|
|
166
|
+
|
|
167
|
+
If you need to output logs in JSON format for ELK, Splunk, or cloud logging (requires `pip install chutils[json]`):
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
# Via code
|
|
171
|
+
logger = setup_logger(json_format=True)
|
|
172
|
+
|
|
173
|
+
# Or via config in the [Logging] section
|
|
174
|
+
# json_format: true
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
#### Contextual Logging (ContextVar)
|
|
178
|
+
|
|
179
|
+
You can bind metadata to the current execution context (thread or coroutine), and it will be automatically
|
|
180
|
+
included in all log messages.
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from chutils import setup_logger, bind_context
|
|
184
|
+
|
|
185
|
+
logger = setup_logger()
|
|
186
|
+
|
|
187
|
+
# Bind request ID and user to the current context
|
|
188
|
+
bind_context(request_id="REQ-123", user="admin")
|
|
189
|
+
|
|
190
|
+
logger.info("Action performed")
|
|
191
|
+
# Text: ... [request_id=REQ-123 user=admin] Action performed
|
|
192
|
+
# JSON: {..., "message": "Action performed", "context": {"request_id": "REQ-123", "user": "admin"}}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
#### Controlling Logging via Environment Variables
|
|
196
|
+
|
|
197
|
+
- `CH_LOG_JSON=true`: Forces JSON format.
|
|
198
|
+
- `CH_LOG_NO_TIME=true`: Removes the date/time from the log format (for clean Docker logs).
|
|
199
|
+
- `CH_LOG_NO_FILE=true`: Disables creating log files.
|
|
200
|
+
|
|
201
|
+
These variables have **highest priority** and override any code or config settings.
|
|
202
|
+
|
|
203
|
+
### 3. Secret Management
|
|
204
|
+
|
|
205
|
+
`SecretManager` looks for secrets in the following order: **Keyring > .env File > Environment Variables**.
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
from chutils import SecretManager
|
|
209
|
+
|
|
210
|
+
secrets = SecretManager("my_awesome_app")
|
|
211
|
+
|
|
212
|
+
# Save once
|
|
213
|
+
secrets.save_secret("API_KEY", "secret-value-123")
|
|
214
|
+
|
|
215
|
+
# Use everywhere
|
|
216
|
+
key = secrets.get_secret("API_KEY")
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
#### Disabling Keyring (Optional)
|
|
220
|
+
|
|
221
|
+
In environments like Docker or CI/CD where `keyring` is unavailable, you can suppress warnings and skip the check:
|
|
222
|
+
|
|
223
|
+
- Set `CH_DISABLE_KEYRING_WARNING=true` in environment.
|
|
224
|
+
- Or add `disable_keyring: true` under `secrets` section in `config.yml`.
|
|
225
|
+
|
|
226
|
+
## API Overview
|
|
227
|
+
|
|
228
|
+
### Configuration (`chutils.config`)
|
|
229
|
+
|
|
230
|
+
- `get_config_value(section, key, fallback)` / `aget_config()`
|
|
231
|
+
- `get_config_int`, `get_config_boolean`, `get_config_list`, `get_config_path`
|
|
232
|
+
- `save_config_value(section, key, value, notify=True)` / `asave_config_value()`
|
|
233
|
+
- Use `notify=False` to update the file without triggering Hot-Reload callbacks.
|
|
234
|
+
|
|
235
|
+
### Logging (`chutils.logger`)
|
|
236
|
+
|
|
237
|
+
- `setup_logger(name, log_level, log_file_name, rotation_type, compress, ...)`
|
|
238
|
+
- Levels: `logger.devdebug` (9), `logger.mediumdebug` (15), and all standard ones.
|
|
239
|
+
|
|
240
|
+
### Secret Management (`chutils.secret_manager`)
|
|
241
|
+
|
|
242
|
+
- `SecretManager(service_name, prefix)`
|
|
243
|
+
- `save_secret` / `asave_secret`
|
|
244
|
+
- `get_secret` / `aget_secret`
|
|
245
|
+
- `delete_secret` / `adelete_secret`
|
|
246
|
+
|
|
247
|
+
### Decorators (`chutils.decorators`)
|
|
248
|
+
|
|
249
|
+
- `@log_function_details`: Logs arguments, execution time, and result (uses `DEVDEBUG` level).
|
|
250
|
+
- `@timeout(seconds, fallback)`: Limits function execution time. Supports sync/async and optional fallback.
|
|
251
|
+
- `@retry`: Automatically retries a function if it fails. Supports sync/async, backoff, jitter, and exception filtering.
|
|
252
|
+
|
|
253
|
+
#### Example of @retry usage:
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
from chutils.decorators import retry
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@retry(retries=3, delay=1.0, backoff=2.0)
|
|
260
|
+
def fetch_data():
|
|
261
|
+
# Will be retried up to 3 times on any Exception
|
|
262
|
+
...
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
## License
|
|
266
|
+
|
|
267
|
+
The project is distributed under the MIT License.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "chutils"
|
|
3
|
+
version = "2.6.0"
|
|
4
|
+
description = "Набор простых и удобных утилит для Python, который избавляет от рутины при работе с конфигурацией и логированием в новых проектах."
|
|
5
|
+
authors = [{name = "Chu4hel", email = "sergeiivanov636@gmail.com"}]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
requires-python = ">=3.9, !=3.9.0, !=3.9.1"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"keyring (>=25.7.0)",
|
|
11
|
+
"pyyaml (>=6.0.3)",
|
|
12
|
+
"python-dotenv (>=1.2.1) ; python_full_version < '3.10'",
|
|
13
|
+
"python-dotenv (>=1.2.2) ; python_full_version >= '3.10'"
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
pydantic = ["pydantic (>=2.13.4,<3.0.0)"]
|
|
18
|
+
json = ["python-json-logger (>=3.2.1)"]
|
|
19
|
+
watch = ["watchdog (>=6.0.0)"]
|
|
20
|
+
full = [
|
|
21
|
+
"pydantic (>=2.13.4)",
|
|
22
|
+
"python-json-logger (>=3.2.1)",
|
|
23
|
+
"watchdog (>=6.0.0)"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
chutils = "chutils.cli:main"
|
|
28
|
+
|
|
29
|
+
[tool.poetry]
|
|
30
|
+
packages = [{ include = "chutils", from = "src" }]
|
|
31
|
+
exclude = [
|
|
32
|
+
"tests/",
|
|
33
|
+
"site/",
|
|
34
|
+
"examples/",
|
|
35
|
+
"docs/",
|
|
36
|
+
".github/",
|
|
37
|
+
".idea/",
|
|
38
|
+
"__pycache__/",
|
|
39
|
+
"*.pyc",
|
|
40
|
+
"*.log",
|
|
41
|
+
"*.egg-info/",
|
|
42
|
+
".vscode/",
|
|
43
|
+
".ruff_cache/",
|
|
44
|
+
"coverage.xml",
|
|
45
|
+
".coverage",
|
|
46
|
+
"PUBLISHING.md",
|
|
47
|
+
"project.txt",
|
|
48
|
+
"changelog.txt",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[tool.poetry.group.dev.dependencies]
|
|
52
|
+
pytest = { version = "^9.0.3", python = ">=3.10" }
|
|
53
|
+
pytest-mock = "^3.15.1"
|
|
54
|
+
pyfakefs = { version = "^6.2.0", python = ">=3.10" }
|
|
55
|
+
mkdocs = "^1.6.1"
|
|
56
|
+
mkdocs-material = "^9.7.5"
|
|
57
|
+
mkdocstrings = { version = "^1.0.4", python = ">=3.10" }
|
|
58
|
+
mkdocstrings-python = { version = "^2.0.3", python = ">=3.10" }
|
|
59
|
+
pytest-cov = "^7.1.0"
|
|
60
|
+
pytest-asyncio = { version = "^1.3.0", python = ">=3.10" }
|
|
61
|
+
ruff = "^0.15.12"
|
|
62
|
+
|
|
63
|
+
[build-system]
|
|
64
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
65
|
+
build-backend = "poetry.core.masonry.api"
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
pythonpath = [
|
|
69
|
+
"src"
|
|
70
|
+
]
|