Skip to main content

Python-box based custom config package (onion_config) for python projects.

Project description

Python Config (onion_config)

Python-box based custom config package (onion_config) for python projects.

Features


Installation

1. Prerequisites

  • Python (>= v3.7)
  • PyPi (>= v21)

2. Install onion-config

A. [RECOMMENDED] PyPi install

# Install or upgrade onion-config package:
pip install --upgrade onion-config

# To uninstall package:
pip uninstall -y onion-config

B. Manually add to PYTHONPATH (Recommended for development)

# Clone repository by git:
git clone https://github.com/bybatkhuu/python_config.git onion_config
cd onion_config

# Install python dependencies:
pip install --upgrade pip
cat requirements.txt | xargs -n 1 -L 1 pip install --no-cache-dir

# Add current path to PYTHONPATH:
export PYTHONPATH="${PWD}:${PYTHONPATH}"

C. Manually compile and setup (Not recommended)

# Clone repository by git:
git clone https://github.com/bybatkhuu/python_config.git onion_config
cd onion_config

# Building python package:
pip install --upgrade pip setuptools wheel
python setup.py build
# Install python dependencies with built package to current python environment:
python setup.py install --record installed_files.txt

# To remove only installed onion-config package:
head -n 1 installed_files.txt | xargs rm -vrf
# Or to remove all installed files and packages:
cat installed_files.txt | xargs rm -vrf

Usage/Examples

Simple example

configs/config.yml:

hostname: "localhost"
username: "admin"
password: "secret"

sample.py:

from pprint import pprint
from onion_config import ConfigBase


_valid_schema = {
    'hostname': { 'type': 'string' },
    'username': { 'type': 'string' },
    'password': { 'type': 'string' },
    'port': { 'type': 'integer', 'coerce': int }
}

def _pre_load(config):
    config.port = '8080'
    config.opt_val = 'optional value'
    return config

config = ConfigBase(pre_load=_pre_load, valid_schema=_valid_schema).load()


if __name__ == '__main__':
    print(config.hostname)
    print(config.username)
    print(config.port)
    print(config.opt_val)
    pprint(config.to_dict())

Advanced example

configs/app.yml:

env: development

app:
    name: "My App"
    host: 0.0.0.0
    port: 80
    secret: "my-secret"
    debug: false

configs/config.json:

{
    "app":
    {
        "logs_dir": "/var/log/app"
    },
    "opt":
    {
        "val": "optional value",
        "integer": 123
    }
}

.env:

ENV=production

APP_PORT=8080
APP_SECRET="My_s3crEt_k3y"

PY_EXTRA_CONFIGS_DIR="./extra_configs"

extra_configs/app.yml:

app:
    name: "My App - Extra"
    description: "Extra description"

utils/validator_schemas.py:

config_schema = {
    'env': { 'type': 'string', 'allowed': ['development', 'production'], 'default': 'development' },
    'app':
    {
        'type': 'dict',
        'schema':
        {
            'name': { 'type': 'string', 'minlength': 2, 'maxlength': 255 },
            'host': { 'type': 'string', 'minlength': 2, 'maxlength': 255 },
            'port': { 'type': 'integer', 'coerce': int, 'min': 1024, 'max': 65535 },
            'secret': { 'type': 'string', 'minlength': 12, 'maxlength': 255 },
            'debug': { 'type': 'boolean' },
            'logs_dir': { 'type': 'string'}
        }
    }
}

config.py:

import os
from onion_config import ConfigBase
from utils.validator_schemas import config_schema


def _pre_load(config):
    try:
        config.env = os.getenv('ENV', config.env).strip().lower()

        if config.env == 'production':
            config.app.debug = False

            if os.getenv('APP_SECRET') is None:
                raise KeyError("Missing required `APP_SECRET` environment variable on 'production'!")

        config.app.port = os.getenv('APP_PORT', config.app.port)
        config.app.debug = os.getenv('APP_DEBUG', config.app.debug)
        config.app.secret = os.getenv('APP_SECRET', config.app.secret)
    except Exception as err:
        print(f"ERROR: Error occured while pre-loading config:\n {err}")
        exit(2)

    return config


config = ConfigBase(pre_load=_pre_load, valid_schema=config_schema).load()

app.py:

from pprint import pprint
from flask import Flask
from config import config


print("LOADED CONFIG:")
pprint(config.to_dict())
print()


app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

if __name__ == '__main__':
    app.run(host=config.app.host, port=config.app.port)

Running Tests

To run tests, run the following command:

pytest

Environment Variables

You can use the following environment variables inside .env file:

PY_EXTRA_CONFIGS_DIR="./extra_configs"

References

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

onion_config-1.0.0.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

onion_config-1.0.0-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file onion_config-1.0.0.tar.gz.

File metadata

  • Download URL: onion_config-1.0.0.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.13

File hashes

Hashes for onion_config-1.0.0.tar.gz
Algorithm Hash digest
SHA256 01adca6d64e3355adee9e1191e3f5f37b34ad175bcf661d876f6afcacca937cf
MD5 503ee0f00f150100e541d0b9707aa16d
BLAKE2b-256 2783be4671170dfa727c0eb1edf8b6856d9788cbf100b4495d9308253c85a7c8

See more details on using hashes here.

File details

Details for the file onion_config-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for onion_config-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6422b96b1edc0e1c0af2f6ddfd7b654eadb0de76cb0f206d6eda273ba8f570d0
MD5 469f3b1e808c239e89b83660255da413
BLAKE2b-256 a6da28c69db81dae72bce851775e7bfd8daedcf81bcc5deba1d9b3fc92054b4e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page