badger-config-handler


Namebadger-config-handler JSON
Version 0.3.1 PyPI version JSON
download
home_page
SummaryConfig handler for code-declared and file-defined settings.
upload_time2023-10-11 21:48:03
maintainer
docs_urlNone
authorpidi3000
requires_python>=3.7
licenseMIT License Copyright (c) 2023 pidi3000 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords settings handler config handler json yaml
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Badger_Config_Handler

A python library for handling code-declared and file-defined settings.

Supports saving to JSON and YAML files.

## Installation

Install from [PyPi](https://pypi.org/project/badger-config-handler/)

``` bash
pip install badger-config-handler
```

## Rules and limitations

1. settings are declared in the class and defined in [setup()](#setup-1)
2. settings **MUST** be declared with a type hint.  example: `my_var: int`
3. settings can only be of [allowed data type](#allowed-data-types)
4. settings not declared in code are ignored in the config file (and are removed on the next save, same for commented out settings)
5. settings can be `None` if they are set to null in the config, regardles of the type hint
6. settings without a default value set in [setup()](#setup-1) are not saved to the config file, but they can still be set from the config file
7. The [root_path](#root_path) and [parent_section](#parent_section) propertys are NOT available in [setup()](#setup-1)

## Example config

``` Python
from pathlib import Path
from badger_config_handler import Badger_Config_Base, Badger_Config_Section

class Sub_Section(Badger_Config_Section):
    section_var: str
    section_float: float

    section_path: Path

    def setup(self):
        self.section_var = "section"
        self.section_float = 20.3
        self.section_path = "relative/sub/path"

    def post_process(self):
        self.section_path = self.make_absolute_to_root(
            relative_path = self.section_path, 
            enforce_in_root = True
        )# becomes "path/to/project/root/relative/sub/path"

    def pre_process(self):
        self.section_path = self.make_relative_to_root(
            absolute_path = self.section_path
        )# turns back to "relative/sub/path"


class base(Badger_Config_Base):
    my_var: str
    my_int: int
    my_none: str
    
    sub_section: Sub_Section # NOT Badger_Config_Section

    def setup(self):
        self.my_var = "test"
        self.my_int = 50
        self.my_none = None
        
        self.sub_section = Sub_Section(section_name="sub")

config = My_Base(
    config_file_path="path/to/config.json",
    root_path="path/to/project/root"
)

config.save()
config.load()
config.sync()
```

## Allowed data types

### native

the file handlers have native support for these types and are used as is,
no conversion is done on these values

- string
- int
- float
- bool
- None / null

---

### supported

#### Badger_Config_Section

converted using

- serialize: `{VAR}.to_dict()`
- de-serialize: `Badger_Config_Section.from_dict({VAR})`

#### datetime.datetime

converted using

- serialize: `{VAR}.isoformat()`
- de-serialize: `datetime.fromisoformat({VAR})`

#### pathlib.Path

converted using

- serialize: `str({VAR})`
- de-serialize: `pathlib.Path({VAR})`

---

### Collections

NOTE:

It is recommended to use a [Config Section](#config-section) instead of Collections.

If collections are used items should be of [native](#native) type only,
if they are not of [native](#native) type they are serialized but can NOT be de-serialize.

Code using these values must handle these cases.

#### dict

#### list

---
---
---

## Config Base

---

### Property's

---

#### _config_file_path

> path to the config file

---

#### ALLOWED_FILE_TYPES

> all allowed file extensions

---
---

### Function's

---

#### setup()

see [Config_Section.setup()](#setup-1)

---

#### save()

Saves config to file

steps:

1. [pre_process()](#pre_process)
2. save to file
3. [post_process()](#post_process)

---

#### load()

Load config from file

**Parameters:**

| param                       | type | required     | default | Note                            |
|-----------------------------|------|--------------|---------|---------------------------------|
| auto_create                 | bool |              | True    | Create config file if not found |
| safe_load [see](#from_dict) | bool |              | True    |  ! UNTESTED !                   |

---

#### sync()

Sync config with file

runs:

1. `load()`
    - if file exists then continue else stop here
2. `save()`
3. `load()`

this adds new config fields to the file or removes old ones

**Parameters:**

same as [load()](#load)

---
---
---

## Config Section

---

### Property's

---

#### section_name

> name of the current section

---

#### root_path

> by default the project root path or overridden by the parent section

---

#### parent_section

> reference to the parent section (if it exists)

---
---

### Function's

---

#### setup()

Replacement for `__init__()`

should be used to set default values

NOTE: the propertys [root_path](#root_path) and [parent_section](#parent_section) are NOT available during this

---

#### pre_process()

Pre process values before [save()](#save)

Warning: the function should be written in a way that running it multiple times in a row doesn't cause problems

useful for:

- converting unsupported data type to a [native](#native) or [supported](#supported) type
- converting [absolute paths to relative](#make_relative_to_rootpath) (keeps them short in the config file)

---

#### post_process()

post process values after [load()](#load)

Warning: the function should be written in a way that running it multiple times in a row doesn't cause problems

useful for:

- creating unsupported data type from [native](#native) or [supported](#supported) type
- converting [relative paths to absolute](#make_absolute_to_rootpath-bool) (keeps them short in the config file)

---

#### make_absolute_to_root(Path, bool)

Help function to make a setting Path absolute to the sections [root_path](#root_path)

Paths settings can escape the root_path using something like `../../secrets.json`.<br>
To avoid that use `enforce_in_root`.

**Parameters:**

| param             | type | required | default |
|-------------------|------|----------|---------|
| relative_path     | Path | x        |         |
| enforce_in_root   | bool |          | True    |

---

#### make_relative_to_root(Path)

Help function to make a setting Path relative to the sections [root_path](#root_path)

**Parameters:**

| param             | type | required | default |
|-------------------|------|----------|---------|
| absolute_path     | Path | x        |         |

---

#### to_dict(bool)

converts all values to a dictionary

**Parameters:**

| param             | type | required | default |
|-------------------|------|----------|---------|
| convert_to_native | bool |          | True    |

---

#### from_dict()

Reconstruct Config Section from dictionary

**Parameters:**

 | param          | type                           | description                                                                                                                        | required | default |
|----------------|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------|----------|---------|
| data           | dict\[str, [native](#native)\] | the dict representation of this section (as generated from [to_dict(True)](#to_dictbool) )                                         | x        |         |
| safe_load      | bool                           | ! UNTESTED ! <br> True -> Only variables that already exist in the class are set (uses `hasattr`) <br> False -> New variables can be set from config file |          | True    |
| danger_convert | bool                           | ! UNTESTED ! <br> For details see docs of `_native_to_var()`                                                                        |          | False   |

---

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "badger-config-handler",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "settings handler,config handler,json,yaml",
    "author": "pidi3000",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/a8/c5/61ec160827a51e86ed5edb3928cf21b7d7595594ca4f084bb77f6ce50ae0/badger-config-handler-0.3.1.tar.gz",
    "platform": null,
    "description": "# Badger_Config_Handler\n\nA python library for handling code-declared and file-defined settings.\n\nSupports saving to JSON and YAML files.\n\n## Installation\n\nInstall from [PyPi](https://pypi.org/project/badger-config-handler/)\n\n``` bash\npip install badger-config-handler\n```\n\n## Rules and limitations\n\n1. settings are declared in the class and defined in [setup()](#setup-1)\n2. settings **MUST** be declared with a type hint.  example: `my_var: int`\n3. settings can only be of [allowed data type](#allowed-data-types)\n4. settings not declared in code are ignored in the config file (and are removed on the next save, same for commented out settings)\n5. settings can be `None` if they are set to null in the config, regardles of the type hint\n6. settings without a default value set in [setup()](#setup-1) are not saved to the config file, but they can still be set from the config file\n7. The [root_path](#root_path) and [parent_section](#parent_section) propertys are NOT available in [setup()](#setup-1)\n\n## Example config\n\n``` Python\nfrom pathlib import Path\nfrom badger_config_handler import Badger_Config_Base, Badger_Config_Section\n\nclass Sub_Section(Badger_Config_Section):\n    section_var: str\n    section_float: float\n\n    section_path: Path\n\n    def setup(self):\n        self.section_var = \"section\"\n        self.section_float = 20.3\n        self.section_path = \"relative/sub/path\"\n\n    def post_process(self):\n        self.section_path = self.make_absolute_to_root(\n            relative_path = self.section_path, \n            enforce_in_root = True\n        )# becomes \"path/to/project/root/relative/sub/path\"\n\n    def pre_process(self):\n        self.section_path = self.make_relative_to_root(\n            absolute_path = self.section_path\n        )# turns back to \"relative/sub/path\"\n\n\nclass base(Badger_Config_Base):\n    my_var: str\n    my_int: int\n    my_none: str\n    \n    sub_section: Sub_Section # NOT Badger_Config_Section\n\n    def setup(self):\n        self.my_var = \"test\"\n        self.my_int = 50\n        self.my_none = None\n        \n        self.sub_section = Sub_Section(section_name=\"sub\")\n\nconfig = My_Base(\n    config_file_path=\"path/to/config.json\",\n    root_path=\"path/to/project/root\"\n)\n\nconfig.save()\nconfig.load()\nconfig.sync()\n```\n\n## Allowed data types\n\n### native\n\nthe file handlers have native support for these types and are used as is,\nno conversion is done on these values\n\n- string\n- int\n- float\n- bool\n- None / null\n\n---\n\n### supported\n\n#### Badger_Config_Section\n\nconverted using\n\n- serialize: `{VAR}.to_dict()`\n- de-serialize: `Badger_Config_Section.from_dict({VAR})`\n\n#### datetime.datetime\n\nconverted using\n\n- serialize: `{VAR}.isoformat()`\n- de-serialize: `datetime.fromisoformat({VAR})`\n\n#### pathlib.Path\n\nconverted using\n\n- serialize: `str({VAR})`\n- de-serialize: `pathlib.Path({VAR})`\n\n---\n\n### Collections\n\nNOTE:\n\nIt is recommended to use a [Config Section](#config-section) instead of Collections.\n\nIf collections are used items should be of [native](#native) type only,\nif they are not of [native](#native) type they are serialized but can NOT be de-serialize.\n\nCode using these values must handle these cases.\n\n#### dict\n\n#### list\n\n---\n---\n---\n\n## Config Base\n\n---\n\n### Property's\n\n---\n\n#### _config_file_path\n\n> path to the config file\n\n---\n\n#### ALLOWED_FILE_TYPES\n\n> all allowed file extensions\n\n---\n---\n\n### Function's\n\n---\n\n#### setup()\n\nsee [Config_Section.setup()](#setup-1)\n\n---\n\n#### save()\n\nSaves config to file\n\nsteps:\n\n1. [pre_process()](#pre_process)\n2. save to file\n3. [post_process()](#post_process)\n\n---\n\n#### load()\n\nLoad config from file\n\n**Parameters:**\n\n| param                       | type | required     | default | Note                            |\n|-----------------------------|------|--------------|---------|---------------------------------|\n| auto_create                 | bool |              | True    | Create config file if not found |\n| safe_load [see](#from_dict) | bool |              | True    |  ! UNTESTED !                   |\n\n---\n\n#### sync()\n\nSync config with file\n\nruns:\n\n1. `load()`\n    - if file exists then continue else stop here\n2. `save()`\n3. `load()`\n\nthis adds new config fields to the file or removes old ones\n\n**Parameters:**\n\nsame as [load()](#load)\n\n---\n---\n---\n\n## Config Section\n\n---\n\n### Property's\n\n---\n\n#### section_name\n\n> name of the current section\n\n---\n\n#### root_path\n\n> by default the project root path or overridden by the parent section\n\n---\n\n#### parent_section\n\n> reference to the parent section (if it exists)\n\n---\n---\n\n### Function's\n\n---\n\n#### setup()\n\nReplacement for `__init__()`\n\nshould be used to set default values\n\nNOTE: the propertys [root_path](#root_path) and [parent_section](#parent_section) are NOT available during this\n\n---\n\n#### pre_process()\n\nPre process values before [save()](#save)\n\nWarning: the function should be written in a way that running it multiple times in a row doesn't cause problems\n\nuseful for:\n\n- converting unsupported data type to a [native](#native) or [supported](#supported) type\n- converting [absolute paths to relative](#make_relative_to_rootpath) (keeps them short in the config file)\n\n---\n\n#### post_process()\n\npost process values after [load()](#load)\n\nWarning: the function should be written in a way that running it multiple times in a row doesn't cause problems\n\nuseful for:\n\n- creating unsupported data type from [native](#native) or [supported](#supported) type\n- converting [relative paths to absolute](#make_absolute_to_rootpath-bool) (keeps them short in the config file)\n\n---\n\n#### make_absolute_to_root(Path, bool)\n\nHelp function to make a setting Path absolute to the sections [root_path](#root_path)\n\nPaths settings can escape the root_path using something like `../../secrets.json`.<br>\nTo avoid that use `enforce_in_root`.\n\n**Parameters:**\n\n| param             | type | required | default |\n|-------------------|------|----------|---------|\n| relative_path     | Path | x        |         |\n| enforce_in_root   | bool |          | True    |\n\n---\n\n#### make_relative_to_root(Path)\n\nHelp function to make a setting Path relative to the sections [root_path](#root_path)\n\n**Parameters:**\n\n| param             | type | required | default |\n|-------------------|------|----------|---------|\n| absolute_path     | Path | x        |         |\n\n---\n\n#### to_dict(bool)\n\nconverts all values to a dictionary\n\n**Parameters:**\n\n| param             | type | required | default |\n|-------------------|------|----------|---------|\n| convert_to_native | bool |          | True    |\n\n---\n\n#### from_dict()\n\nReconstruct Config Section from dictionary\n\n**Parameters:**\n\n | param          | type                           | description                                                                                                                        | required | default |\n|----------------|--------------------------------|------------------------------------------------------------------------------------------------------------------------------------|----------|---------|\n| data           | dict\\[str, [native](#native)\\] | the dict representation of this section (as generated from [to_dict(True)](#to_dictbool) )                                         | x        |         |\n| safe_load      | bool                           | ! UNTESTED ! <br> True -> Only variables that already exist in the class are set (uses `hasattr`) <br> False -> New variables can be set from config file |          | True    |\n| danger_convert | bool                           | ! UNTESTED ! <br> For details see docs of `_native_to_var()`                                                                        |          | False   |\n\n---\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 pidi3000  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Config handler for code-declared and file-defined settings.",
    "version": "0.3.1",
    "project_urls": {
        "Repository": "https://github.com/pidi3000/Badger_Config_Handler"
    },
    "split_keywords": [
        "settings handler",
        "config handler",
        "json",
        "yaml"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f619e8a174643c678343553ec965d252cd4cd13473aaeeb32ad0b2e6718a4ac1",
                "md5": "88716df60c1b5a7947413e09c4223e99",
                "sha256": "8fa02e5db136f78601bfd82ef2c8da81a4eff862e8289f70d9ecd4d6fcf99ed0"
            },
            "downloads": -1,
            "filename": "badger_config_handler-0.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "88716df60c1b5a7947413e09c4223e99",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 14364,
            "upload_time": "2023-10-11T21:48:02",
            "upload_time_iso_8601": "2023-10-11T21:48:02.021824Z",
            "url": "https://files.pythonhosted.org/packages/f6/19/e8a174643c678343553ec965d252cd4cd13473aaeeb32ad0b2e6718a4ac1/badger_config_handler-0.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a8c561ec160827a51e86ed5edb3928cf21b7d7595594ca4f084bb77f6ce50ae0",
                "md5": "86eb24cc1e9bc922f79c2eb21113e050",
                "sha256": "3f8257d9af9caa2a484362d4317643e586e69d9e9a3c453d41e9016bb443e117"
            },
            "downloads": -1,
            "filename": "badger-config-handler-0.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "86eb24cc1e9bc922f79c2eb21113e050",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 16566,
            "upload_time": "2023-10-11T21:48:03",
            "upload_time_iso_8601": "2023-10-11T21:48:03.847806Z",
            "url": "https://files.pythonhosted.org/packages/a8/c5/61ec160827a51e86ed5edb3928cf21b7d7595594ca4f084bb77f6ce50ae0/badger-config-handler-0.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-11 21:48:03",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pidi3000",
    "github_project": "Badger_Config_Handler",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "badger-config-handler"
}
        
Elapsed time: 0.12061s