Skip to content

Commit

Permalink
upd
Browse files Browse the repository at this point in the history
  • Loading branch information
morington committed Jun 27, 2024
1 parent 5bbbe74 commit 9b26bd4
Showing 1 changed file with 128 additions and 66 deletions.
194 changes: 128 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,103 +1,165 @@
# ConfHub
![](./logo.png)

**Данный модуль позволяет загружать и обрабатывать конфигурационные файлы различных форматов:**
- `.toml`
- `.yaml`
- `.json`
- `.ini`
- `.py`
- `.env`
<p align="center">
<img alt="PyPI - Status" src="https://img.shields.io/pypi/status/confhub">
<img alt="PyPI - Version" src="https://img.shields.io/pypi/v/confhub">
<img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/confhub">
<img alt="PyPI - License" src="https://img.shields.io/pypi/l/confhub">
</p>

### !! В конфигурации определена настройка логов с помощью `structlog` и моей настройки процессоров !!
*********
## About
<b>Сonfhub</b> is a library that relieves developers of the tedious task of creating and managing configuration files. Instead of wasting valuable time writing configurations, developers can focus on building the site's functionality.

# Основные возможности:
### History
Based on our own experience and the experience of our colleagues, we realized that the process of working with configurations had become a real burden. We wanted something simple and effective. After several weeks of testing our MVP, we identified the strengths and weaknesses and presented the first alpha version of confhub to the world. Despite its shortcomings, it showed prospects for development.

- *Парсинг файлов конфигурации и объединение данных в единый словарь*
- *Автоматическое создание URL-адресов для сервисов по их настройкам*
- *Поддержка работы с переменными окружения (.env файлы)*
- *Возможность задания приоритетных настроек для разработки*
- *Использование модуля позволяет упростить доступ к конфигурационным данным в коде проекта, а также автоматизировать ряд рутинных задач, связанных с конфигурацией.*
### Updated version (>= 0.1.0.5a)
We currently offer a significantly improved version of confhub, which has extensive functionality. You can now dynamically generate configurations from model classes, greatly simplifying the process. In addition, the library supports developer mode, which speeds up the process of replacing configurations several times.

# Установка
*********
## Documentation

```console
### Getting started with confhub

*********
**Installation and initialization**

To get started with confhub, you need to create a project and install the Python virtual environment. Then install the confhub library into the virtual environment.

```bash
pip install confhub
```

# Использование
After installing the library, initialize it in your project with the following command:

```bash
confhub init <folder>
```

Вы можете автоматически сгенерировать файлы конфигурации в удобное место:
Where `<folder>` is the name of the folder where the entire configuration structure will be placed. For example:

```console
confhub --create config
```bash
confhub init configurations
```

*confhub -c/--create **название_вашей папки***
This command will create the following structure in the root of your project:

- `.service.yml`: Contains basic settings such as paths to configs and models. The file is automatically added to `.gitignore`.
- `configurations/`: A folder created at your request.
- `config/`: A folder to store the generated configuration files.
- `models.py`: A file for describing models. Initially contains an example PostgreSQL model.

Для генерации файлов в текущую папку используйте точку:
*********
**Creating Models**

```console
confhub -c .
In `models.py` you can describe your models. For example:

```python
from confhub import BlockCore, field

class PostgreSQL(BlockCore):
__block__ = 'postgresql'

scheme = field(str)
host = field(str, development_mode=True)
port = field(int, secret=True)
user = field(str, secret=True)
password = field(str, secret=True)
path = field(str, secret=True)

class ItemBlock(BlockCore):
__block__ = 'item_block'

item_name = field(str)

class TestBlock(BlockCore):
__block__ = 'test_block'

item_block = ItemBlock()
illuminati = field(str, filename='illuminati')
admins = field(str)
```

Если папки не существует, confhub запросит у пользователя подтверждение о создание папки:
*********
**Generation of configuration files**

```console
confhub -c test
After creating models, you can generate configuration files using the command:

Do you want to create a new folder at (D:\ConfHub\test)? [Y/n]
: y
2024-05-08 13:00:38 [info ] Loading configuration files [commands.py:generate_configurations_files:32] secret_file=WindowsPath('D:/ConfHub/test/.secrets.yml') secret_file__example=WindowsPath('D:/ConfHub/test/example__secrets.yml') settings=WindowsPath('D:/ConfHub/test/settings.yml')
```bash
confhub generate_models
```

Далее вы можете использовать конфигурацию в вашем коде:
This command converts your models into configuration files with a `.yml` extension.

```python
from confhub.reader import ReaderConf
Confhub generates two main files: `settings` and `.secrets`. The secrets are automatically added to `.gitignore`. You can also specify `filename` in models to create additional files in the `config` folder.

reader = ReaderConf('config/settings.yml', 'config/.secrets.yml', dev=True)
reader.create_service_urls()
configuration = reader.data
__Do not use `secrets` and `filename` at the same time. There may be unexpected consequences at this point!__

assert configuration.get('postgresql_url') == 'postgresql+asyncpg://ghost:qwerty@127.0.0.1:5432/database'
# True
This documentation will help you get started with confhub and use its features to simplify the process of working with configurations in your project.

*********
**Filling configurations**

Fill in the configurations, e.g:

```yaml
postgresql:
password: str; qwer
path: str; db_confhub
port: int; 5432
user: str; morington
```
По умолчанию используется глобальная конфигурация для логирования с режимом DEBUG:
The data type is specified before the value. Available types: `str`, `int`, `bool`, `float`. YML also supports lists, in models we prescribe a type for the value of each element in a list, and with YML we make a list:

```yaml
admins:
- str; Adam
- str; John
- str; Saly
```

*********
**Read configurations**

To read configurations, use the following code:

```python
import structlog
from confhub import Confhub
from confhub.setup_logger import LoggerReg
logger_registrations = [
LoggerReg(name="", level=LoggerReg.Level.DEBUG)
]
logger = structlog.get_logger(__name__)
if __name__ == '__main__':
config = Confhub(developer_mode=True, logger_regs=[
LoggerReg(name="", level=LoggerReg.Level.DEBUG,)
]).data
logger.info("PostgreSQL", host=config.postgresql.host)
logger.info("Admins", host=config.test.admins)
```

Чтобы изменить ее передайте в параметр ReaderConf ваши настройки:
*********
**Logging Configuration**

Sonfhub uses `structlog` for logging. You can configure loggers using ``LoggerReg``:

```python
from confhub.reader import ReaderConf
from confhub.setup_logger import LoggerReg
"""
class Level(Enum):
DEBUG: str = "DEBUG"
INFO: str = "INFO"
WARNING: str = "WARNING"
ERROR: str = "ERROR"
CRITICAL: str = "CRITICAL"
NONE: str = None
"""

reader = ReaderConf(
'config/settings.yml', 'config/.secrets.yml', dev=True,
logger_registrations = [
LoggerReg(name="название вашего логера", level=LoggerReg.Level.INFO),
LoggerReg(name="название вашего следующего логера", level=LoggerReg.Level.ERROR),
# и так далее
]
)
LoggerReg(name="", level=LoggerReg.Level.DEBUG)
```

## Внимание!
*********
**developer_mode**

The `developer_mode` argument is available both in the `Confhub` class and in the `.service.yml` file. The class argument takes precedence over the file.

*********
## Main developers

### [Adam Morington](https://github.com/morington)

Настройки логирования с записью в файл пока на экспериментальном уровне. Пожалуйста, сообщайте о всех багах мне в [личку телеграм](https://t.me/morington).
*********
## License
[Сonfhub](https://github.com/morington/help) is distributed under the [MIT license](https://github.com/morington/help/blob/main/LICENSE). This means that you are free to use, modify and distribute the library for any purpose, including commercial use.

0 comments on commit 9b26bd4

Please sign in to comment.