somestuff-corestuff 0.1.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.
@@ -0,0 +1,180 @@
1
+ /**/.gtfs_cache
2
+ /*.local
3
+ .claude
4
+
5
+ /*gguf*
6
+
7
+ /docker-config
8
+ /docker_build_local.log
9
+
10
+ /ms?hit
11
+ *mstest*py
12
+ *_test.py
13
+ /umqtt
14
+ .idea/
15
+ /upydev_.config
16
+ *.local.*
17
+ /scripts/logdir/
18
+
19
+
20
+ # Byte-compiled / optimized / DLL files
21
+ __pycache__/
22
+ *.py[cod]
23
+ *$py.class
24
+
25
+ # C extensions
26
+ *.so
27
+
28
+ # Distribution / packaging
29
+ .Python
30
+ build/
31
+ develop-eggs/
32
+ dist/
33
+ downloads/
34
+ eggs/
35
+ .eggs/
36
+ lib/
37
+ lib64/
38
+ parts/
39
+ sdist/
40
+ var/
41
+ wheels/
42
+ share/python-wheels/
43
+ *.egg-info/
44
+ .installed.cfg
45
+ *.egg
46
+ MANIFEST
47
+
48
+ # PyInstaller
49
+ # Usually these files are written by a python script from a template
50
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
51
+ *.manifest
52
+ *.spec
53
+
54
+ # Installer logs
55
+ pip-log.txt
56
+ pip-delete-this-directory.txt
57
+
58
+ # Unit test / coverage reports
59
+ htmlcov/
60
+ .tox/
61
+ .nox/
62
+ .coverage
63
+ .coverage.*
64
+ .cache
65
+ nosetests.xml
66
+ coverage.xml
67
+ *.cover
68
+ *.py,cover
69
+ .hypothesis/
70
+ .pytest_cache/
71
+ cover/
72
+
73
+ # Translations
74
+ *.mo
75
+ *.pot
76
+
77
+ # Django stuff:
78
+ *.log
79
+ local_settings.py
80
+ db.sqlite3
81
+ db.sqlite3-journal
82
+
83
+ # Flask stuff:
84
+ instance/
85
+ .webassets-cache
86
+
87
+ # Scrapy stuff:
88
+ .scrapy
89
+
90
+ # Sphinx documentation
91
+ docs/_build/
92
+
93
+ # PyBuilder
94
+ .pybuilder/
95
+ target/
96
+
97
+ # Jupyter Notebook
98
+ .ipynb_checkpoints
99
+
100
+ # IPython
101
+ profile_default/
102
+ ipython_config.py
103
+
104
+ # pyenv
105
+ # For a library or package, you might want to ignore these files since the code is
106
+ # intended to run in multiple environments; otherwise, check them in:
107
+ # .python-version
108
+
109
+ # pipenv
110
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
111
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
112
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
113
+ # install all needed dependencies.
114
+ #Pipfile.lock
115
+
116
+ # poetry
117
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
118
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
119
+ # commonly ignored for libraries.
120
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
121
+ #poetry.lock
122
+
123
+ # pdm
124
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
125
+ #pdm.lock
126
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
127
+ # in version control.
128
+ # https://pdm.fming.dev/#use-with-ide
129
+ .pdm.toml
130
+
131
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
132
+ __pypackages__/
133
+
134
+ # Celery stuff
135
+ celerybeat-schedule
136
+ celerybeat.pid
137
+
138
+ # SageMath parsed files
139
+ *.sage.py
140
+
141
+ # Environments
142
+ .env
143
+ .venv
144
+ env/
145
+ venv/
146
+ ENV/
147
+ env.bak/
148
+ venv.bak/
149
+
150
+ # Spyder project settings
151
+ .spyderproject
152
+ .spyproject
153
+
154
+ # Rope project settings
155
+ .ropeproject
156
+
157
+ # mkdocs documentation
158
+ /site
159
+
160
+ # mypy
161
+ .mypy_cache/
162
+ .dmypy.json
163
+ dmypy.json
164
+
165
+ # Pyre type checker
166
+ .pyre/
167
+
168
+ # pytype static type analyzer
169
+ .pytype/
170
+
171
+ # Cython debug symbols
172
+ cython_debug/
173
+
174
+ # PyCharm
175
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
176
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
177
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
178
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
179
+ #.idea/
180
+
@@ -0,0 +1,163 @@
1
+ GNU Lesser General Public License
2
+ =================================
3
+
4
+ _Version 3, 29 June 2007_
5
+ _Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+
11
+ This version of the GNU Lesser General Public License incorporates
12
+ the terms and conditions of version 3 of the GNU General Public
13
+ License, supplemented by the additional permissions listed below.
14
+
15
+ ### 0. Additional Definitions
16
+
17
+ As used herein, “this License” refers to version 3 of the GNU Lesser
18
+ General Public License, and the “GNU GPL” refers to version 3 of the GNU
19
+ General Public License.
20
+
21
+ “The Library” refers to a covered work governed by this License,
22
+ other than an Application or a Combined Work as defined below.
23
+
24
+ An “Application” is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A “Combined Work” is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the “Linked
32
+ Version”.
33
+
34
+ The “Minimal Corresponding Source” for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The “Corresponding Application Code” for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ ### 1. Exception to Section 3 of the GNU GPL
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ ### 2. Conveying Modified Versions
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ * **a)** under this License, provided that you make a good faith effort to
58
+ ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+
62
+ * **b)** under the GNU GPL, with none of the additional permissions of
63
+ this License applicable to that copy.
64
+
65
+ ### 3. Object Code Incorporating Material from Library Header Files
66
+
67
+ The object code form of an Application may incorporate material from
68
+ a header file that is part of the Library. You may convey such object
69
+ code under terms of your choice, provided that, if the incorporated
70
+ material is not limited to numerical parameters, data structure
71
+ layouts and accessors, or small macros, inline functions and templates
72
+ (ten or fewer lines in length), you do both of the following:
73
+
74
+ * **a)** Give prominent notice with each copy of the object code that the
75
+ Library is used in it and that the Library and its use are
76
+ covered by this License.
77
+ * **b)** Accompany the object code with a copy of the GNU GPL and this license
78
+ document.
79
+
80
+ ### 4. Combined Works
81
+
82
+ You may convey a Combined Work under terms of your choice that,
83
+ taken together, effectively do not restrict modification of the
84
+ portions of the Library contained in the Combined Work and reverse
85
+ engineering for debugging such modifications, if you also do each of
86
+ the following:
87
+
88
+ * **a)** Give prominent notice with each copy of the Combined Work that
89
+ the Library is used in it and that the Library and its use are
90
+ covered by this License.
91
+
92
+ * **b)** Accompany the Combined Work with a copy of the GNU GPL and this license
93
+ document.
94
+
95
+ * **c)** For a Combined Work that displays copyright notices during
96
+ execution, include the copyright notice for the Library among
97
+ these notices, as well as a reference directing the user to the
98
+ copies of the GNU GPL and this license document.
99
+
100
+ * **d)** Do one of the following:
101
+ - **0)** Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+ - **1)** Use a suitable shared library mechanism for linking with the
109
+ Library. A suitable mechanism is one that **(a)** uses at run time
110
+ a copy of the Library already present on the user's computer
111
+ system, and **(b)** will operate properly with a modified version
112
+ of the Library that is interface-compatible with the Linked
113
+ Version.
114
+
115
+ * **e)** Provide Installation Information, but only if you would otherwise
116
+ be required to provide such information under section 6 of the
117
+ GNU GPL, and only to the extent that such information is
118
+ necessary to install and execute a modified version of the
119
+ Combined Work produced by recombining or relinking the
120
+ Application with a modified version of the Linked Version. (If
121
+ you use option **4d0**, the Installation Information must accompany
122
+ the Minimal Corresponding Source and Corresponding Application
123
+ Code. If you use option **4d1**, you must provide the Installation
124
+ Information in the manner specified by section 6 of the GNU GPL
125
+ for conveying Corresponding Source.)
126
+
127
+ ### 5. Combined Libraries
128
+
129
+ You may place library facilities that are a work based on the
130
+ Library side by side in a single library together with other library
131
+ facilities that are not Applications and are not covered by this
132
+ License, and convey such a combined library under terms of your
133
+ choice, if you do both of the following:
134
+
135
+ * **a)** Accompany the combined library with a copy of the same work based
136
+ on the Library, uncombined with any other library facilities,
137
+ conveyed under the terms of this License.
138
+ * **b)** Give prominent notice with the combined library that part of it
139
+ is a work based on the Library, and explaining where to find the
140
+ accompanying uncombined form of the same work.
141
+
142
+ ### 6. Revised Versions of the GNU Lesser General Public License
143
+
144
+ The Free Software Foundation may publish revised and/or new versions
145
+ of the GNU Lesser General Public License from time to time. Such new
146
+ versions will be similar in spirit to the present version, but may
147
+ differ in detail to address new problems or concerns.
148
+
149
+ Each version is given a distinguishing version number. If the
150
+ Library as you received it specifies that a certain numbered version
151
+ of the GNU Lesser General Public License “or any later version”
152
+ applies to it, you have the option of following the terms and
153
+ conditions either of that published version or of any later version
154
+ published by the Free Software Foundation. If the Library as you
155
+ received it does not specify a version number of the GNU Lesser
156
+ General Public License, you may choose any version of the GNU Lesser
157
+ General Public License ever published by the Free Software Foundation.
158
+
159
+ If the Library as you received it specifies that a proxy can decide
160
+ whether future versions of the GNU Lesser General Public License shall
161
+ apply, that proxy's public statement of acceptance of any version is
162
+ permanent authorization for you to choose that version for the
163
+ Library.
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.5
2
+ Name: somestuff-corestuff
3
+ Version: 0.1.0
4
+ Summary: Shared settings loader for the somestuff packages: pydantic-settings over config.yaml with config.local.yaml overrides from the working directory, plus JSON/dict helpers
5
+ Project-URL: Homepage, https://github.com/vroomfondel/somestuff
6
+ Project-URL: Repository, https://github.com/vroomfondel/somestuff
7
+ Project-URL: Issues, https://github.com/vroomfondel/somestuff/issues
8
+ Author-email: Henning Thieß <ht@xomox.cc>
9
+ License-File: LICENSE.md
10
+ Keywords: configuration,iot,pydantic-settings,yaml
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.13
21
+ Requires-Dist: cachetools>=5.5
22
+ Requires-Dist: email-validator>=2.2
23
+ Requires-Dist: loguru>=0.7.3
24
+ Requires-Dist: pydantic-extra-types>=2.10
25
+ Requires-Dist: pydantic-settings>=2.10
26
+ Requires-Dist: pydantic>=2.11
27
+ Requires-Dist: pytz>=2025.1
28
+ Requires-Dist: ruamel-yaml>=0.18
29
+ Description-Content-Type: text/markdown
30
+
31
+ # somestuff-corestuff
32
+
33
+ Shared settings loader for the `somestuff.*` packages that read the repo-wide `config.yaml`
34
+ (`ecowittstuff`, `netatmostuff`, `hydromailstuff`, `llmstuff`).
35
+
36
+ ```python
37
+ from somestuff.corestuff.config import get_settings, get_timezone, settings
38
+
39
+ get_settings().mqtt.host # explicit
40
+ settings.mqtt.host # lazy proxy, same object
41
+ ```
42
+
43
+ Nothing is read at import time. The first access loads, in this order of precedence:
44
+
45
+ | Source | Where it is looked for |
46
+ |-----------------------------|----------------------------------------------------------------------------------------------|
47
+ | environment variables | nested with `__`, e.g. `MQTT__HOST=broker` |
48
+ | `config.local.yaml` | `SOMESTUFF_CONFIG_LOCAL_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app` |
49
+ | `config.yaml` | `SOMESTUFF_CONFIG_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app`, else the packaged sample |
50
+
51
+ `config.local.yaml` carries the secrets and is never part of a distribution; keep it in the directory you start the tool from.
52
+ `python3 -m somestuff.corestuff.config` (or `somestuff-config-dump`) prints the effective settings.
53
+
54
+ `somestuff.corestuff.configure_logging()` installs the shared loguru format and routes stdlib `logging` into it;
55
+ `somestuff.corestuff.helper` has the JSON encoder (`ComplexEncoder`) and `update_deep()`.
@@ -0,0 +1,25 @@
1
+ # somestuff-corestuff
2
+
3
+ Shared settings loader for the `somestuff.*` packages that read the repo-wide `config.yaml`
4
+ (`ecowittstuff`, `netatmostuff`, `hydromailstuff`, `llmstuff`).
5
+
6
+ ```python
7
+ from somestuff.corestuff.config import get_settings, get_timezone, settings
8
+
9
+ get_settings().mqtt.host # explicit
10
+ settings.mqtt.host # lazy proxy, same object
11
+ ```
12
+
13
+ Nothing is read at import time. The first access loads, in this order of precedence:
14
+
15
+ | Source | Where it is looked for |
16
+ |-----------------------------|----------------------------------------------------------------------------------------------|
17
+ | environment variables | nested with `__`, e.g. `MQTT__HOST=broker` |
18
+ | `config.local.yaml` | `SOMESTUFF_CONFIG_LOCAL_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app` |
19
+ | `config.yaml` | `SOMESTUFF_CONFIG_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app`, else the packaged sample |
20
+
21
+ `config.local.yaml` carries the secrets and is never part of a distribution; keep it in the directory you start the tool from.
22
+ `python3 -m somestuff.corestuff.config` (or `somestuff-config-dump`) prints the effective settings.
23
+
24
+ `somestuff.corestuff.configure_logging()` installs the shared loguru format and routes stdlib `logging` into it;
25
+ `somestuff.corestuff.helper` has the JSON encoder (`ComplexEncoder`) and `update_deep()`.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "somestuff-corestuff"
7
+ dynamic = ["version"]
8
+ description = "Shared settings loader for the somestuff packages: pydantic-settings over config.yaml with config.local.yaml overrides from the working directory, plus JSON/dict helpers"
9
+ readme = "README.md"
10
+ requires-python = ">=3.13"
11
+ authors = [{ name = "Henning Thieß", email = "ht@xomox.cc" }]
12
+ license-files = ["LICENSE.md"]
13
+ keywords = ["configuration", "pydantic-settings", "yaml", "iot"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: System Administrators",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Topic :: Software Development :: Libraries",
21
+ "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
22
+ "Operating System :: POSIX :: Linux",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = [
26
+ "loguru>=0.7.3",
27
+ "pydantic>=2.11",
28
+ "pydantic-settings>=2.10",
29
+ "pydantic-extra-types>=2.10",
30
+ "email-validator>=2.2",
31
+ "ruamel.yaml>=0.18",
32
+ "pytz>=2025.1",
33
+ "cachetools>=5.5",
34
+ ]
35
+
36
+ [project.scripts]
37
+ somestuff-config-dump = "somestuff.corestuff.config:log_settings"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/vroomfondel/somestuff"
41
+ Repository = "https://github.com/vroomfondel/somestuff"
42
+ Issues = "https://github.com/vroomfondel/somestuff/issues"
43
+
44
+ [tool.hatch.version]
45
+ path = "somestuff/corestuff/__init__.py"
46
+
47
+ # Build-level selection governs sdist AND wheel; a wheel-only `packages` leaves the sdist unscoped.
48
+ # A target-level `exclude` replaces the build-level list instead of extending it, so each target carries the full set.
49
+ [tool.hatch.build]
50
+ packages = ["somestuff"]
51
+ exclude = ["**/__pycache__", "**/*.pyc", "**/*.local.*", "**/*_deployment.yml", "**/*_cronjob.yml", "**/*.example", "**/*.example.yaml", "**/*.sh"]
52
+
53
+ [tool.hatch.build.targets.sdist]
54
+ exclude = ["**/__pycache__", "**/*.pyc", "**/*.local.*", "**/*_deployment.yml", "**/*_cronjob.yml", "**/*.example", "**/*.example.yaml", "**/*.sh"]
55
+
56
+ [tool.hatch.build.targets.wheel]
57
+ exclude = ["**/__pycache__", "**/*.pyc", "**/*.local.*", "**/*_deployment.yml", "**/*_cronjob.yml", "**/*.example", "**/*.example.yaml", "**/*.sh", "**/README.md"]
@@ -0,0 +1,25 @@
1
+ # somestuff-corestuff
2
+
3
+ Shared settings loader for the `somestuff.*` packages that read the repo-wide `config.yaml`
4
+ (`ecowittstuff`, `netatmostuff`, `hydromailstuff`, `llmstuff`).
5
+
6
+ ```python
7
+ from somestuff.corestuff.config import get_settings, get_timezone, settings
8
+
9
+ get_settings().mqtt.host # explicit
10
+ settings.mqtt.host # lazy proxy, same object
11
+ ```
12
+
13
+ Nothing is read at import time. The first access loads, in this order of precedence:
14
+
15
+ | Source | Where it is looked for |
16
+ |-----------------------------|----------------------------------------------------------------------------------------------|
17
+ | environment variables | nested with `__`, e.g. `MQTT__HOST=broker` |
18
+ | `config.local.yaml` | `SOMESTUFF_CONFIG_LOCAL_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app` |
19
+ | `config.yaml` | `SOMESTUFF_CONFIG_PATH`, else `SOMESTUFF_CONFIG_DIR_PATH`, else the CWD, else `/app`, else the packaged sample |
20
+
21
+ `config.local.yaml` carries the secrets and is never part of a distribution; keep it in the directory you start the tool from.
22
+ `python3 -m somestuff.corestuff.config` (or `somestuff-config-dump`) prints the effective settings.
23
+
24
+ `somestuff.corestuff.configure_logging()` installs the shared loguru format and routes stdlib `logging` into it;
25
+ `somestuff.corestuff.helper` has the JSON encoder (`ComplexEncoder`) and `update_deep()`.
@@ -0,0 +1,57 @@
1
+ """corestuff — shared settings loader (pydantic-settings over config.yaml + config.local.yaml) and helpers.
2
+
3
+ Lookup order for ``config.yaml``: ``SOMESTUFF_CONFIG_PATH``, ``SOMESTUFF_CONFIG_DIR_PATH``, the current
4
+ directory, ``/app``, then the packaged sample. ``config.local.yaml`` is searched the same way
5
+ (``SOMESTUFF_CONFIG_LOCAL_PATH``) and merged over it. Nothing is read at import time: call
6
+ :func:`somestuff.corestuff.config.get_settings`, or use the lazy ``settings`` proxy.
7
+ """
8
+
9
+ import inspect
10
+ import logging
11
+ import os
12
+ import sys
13
+ from collections.abc import Callable
14
+ from types import FrameType
15
+ from typing import TYPE_CHECKING
16
+
17
+ from loguru import logger as glogger
18
+
19
+ if TYPE_CHECKING:
20
+ from loguru import Record
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = ["__version__", "configure_logging"]
25
+
26
+
27
+ def _loguru_skiplog_filter(record: "Record") -> bool:
28
+ return not record.get("extra", {}).get("skiplog", False)
29
+
30
+
31
+ class _InterceptHandler(logging.Handler):
32
+ def emit(self, record: logging.LogRecord) -> None:
33
+ level: str | int
34
+ try:
35
+ level = glogger.level(record.levelname).name
36
+ except ValueError:
37
+ level = record.levelno
38
+ frame: FrameType | None = inspect.currentframe()
39
+ depth = 0
40
+ while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
41
+ frame = frame.f_back
42
+ depth += 1
43
+ glogger.bind(classname=record.name).opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
44
+
45
+
46
+ def configure_logging(
47
+ verbose: bool = False, loguru_filter: Callable[["Record"], bool] = _loguru_skiplog_filter
48
+ ) -> None:
49
+ level_name: str = "DEBUG" if verbose else os.getenv("LOGURU_LEVEL", "INFO")
50
+ os.environ["LOGURU_LEVEL"] = level_name
51
+ glogger.remove()
52
+ logger_fmt: str = (
53
+ "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{module}</cyan>::<cyan>{extra[classname]}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
54
+ )
55
+ glogger.add(sys.stderr, level=level_name, format=logger_fmt, filter=loguru_filter) # type: ignore[arg-type]
56
+ glogger.configure(extra={"classname": "None", "skiplog": False})
57
+ logging.basicConfig(handlers=[_InterceptHandler()], level=logging.getLevelNamesMapping()[level_name], force=True)
@@ -0,0 +1,291 @@
1
+ import datetime
2
+ import json
3
+ import os
4
+ from functools import lru_cache
5
+ from pathlib import Path
6
+ from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, cast
7
+
8
+ import pytz
9
+ from cachetools import TTLCache, cached
10
+ from loguru import logger
11
+ from pydantic import BaseModel, EmailStr, Field, HttpUrl, model_validator
12
+ from pydantic.networks import IPvAnyAddress
13
+ from pydantic_extra_types.mac_address import MacAddress
14
+ from pydantic_settings import (
15
+ BaseSettings,
16
+ DotEnvSettingsSource,
17
+ EnvSettingsSource,
18
+ InitSettingsSource,
19
+ PydanticBaseSettingsSource,
20
+ SettingsConfigDict,
21
+ )
22
+ from ruamel.yaml import YAML
23
+
24
+ from somestuff.corestuff import helper
25
+
26
+ _PKG = "SOMESTUFF"
27
+ _PACKAGE_DIR: Path = Path(__file__).parent.resolve()
28
+ _CONFIG_FILENAME = "config.yaml"
29
+ _CONFIG_LOCAL_FILENAME = "config.local.yaml"
30
+
31
+
32
+ def _search_dirs() -> List[Path]:
33
+ env_dir: str | None = os.getenv(f"{_PKG}_CONFIG_DIR_PATH")
34
+ if env_dir:
35
+ return [Path(env_dir)]
36
+ return [Path.cwd(), Path("/app")]
37
+
38
+
39
+ def _first_existing(filename: str) -> Path | None:
40
+ for d in _search_dirs():
41
+ candidate: Path = Path(d, filename)
42
+ if candidate.is_file():
43
+ return candidate
44
+ return None
45
+
46
+
47
+ def config_path() -> Path:
48
+ env_path: str | None = os.getenv(f"{_PKG}_CONFIG_PATH")
49
+ if env_path:
50
+ return Path(env_path)
51
+ return _first_existing(_CONFIG_FILENAME) or Path(_PACKAGE_DIR, _CONFIG_FILENAME)
52
+
53
+
54
+ def config_local_path() -> Path | None:
55
+ env_path: str | None = os.getenv(f"{_PKG}_CONFIG_LOCAL_PATH")
56
+ if env_path:
57
+ return Path(env_path)
58
+ return _first_existing(_CONFIG_LOCAL_FILENAME)
59
+
60
+
61
+ def _load_yaml(path: Path | None) -> Dict[str, Any] | None:
62
+ if path is None or not path.is_file():
63
+ return None
64
+ try:
65
+ return YAML().load(path)
66
+ except Exception as e:
67
+ logger.opt(exception=e).exception(f"Error loading config file: {path}")
68
+ return None
69
+
70
+
71
+ @lru_cache(maxsize=1)
72
+ def get_effective_config() -> Dict[str, Any]:
73
+ base: Dict[str, Any] | None = _load_yaml(config_path())
74
+ local: Dict[str, Any] | None = _load_yaml(config_local_path())
75
+ if base is None:
76
+ return {} if local is None else local
77
+ if local is None:
78
+ return base
79
+ return cast(Dict[str, Any], helper.update_deep(base, local))
80
+
81
+
82
+ class _EffectiveConfigSource(PydanticBaseSettingsSource):
83
+ def get_field_value(self, field: Any, field_name: str) -> Tuple[Any, str, bool]:
84
+ return None, field_name, False
85
+
86
+ def __call__(self) -> Dict[str, Any]:
87
+ return dict(get_effective_config())
88
+
89
+
90
+ # alias in settings not correctly handled for pydantic v2
91
+ # https://github.com/pydantic/pydantic/issues/8379
92
+
93
+
94
+ class MqttTopic(BaseModel):
95
+ # modulename: str
96
+ # submodulename: str
97
+ topic: str
98
+ subscribe: bool = False
99
+
100
+
101
+ class MqttTopics(BaseModel):
102
+ root: Dict[str, Dict[str, MqttTopic]]
103
+
104
+ @model_validator(mode="before")
105
+ @classmethod
106
+ def _populate_root(cls, v: Any) -> Any:
107
+ if isinstance(v, dict) and "root" not in v:
108
+ return {"root": v}
109
+ return v
110
+
111
+ def __iter__(self) -> Any:
112
+ return iter(self.root) # type: ignore
113
+
114
+ def __getitem__(self, item: Any) -> Any:
115
+ return self.root[item]
116
+
117
+
118
+ class NetatmoModule(BaseModel):
119
+ name: str
120
+ id: Optional[MacAddress] = None
121
+
122
+
123
+ class Netatmo(BaseModel):
124
+ username: str
125
+ password: str
126
+ client_id: str
127
+ client_secret: str
128
+ refresh_token: Optional[str] = None
129
+ outdoormodule: NetatmoModule
130
+ rainmodule: NetatmoModule
131
+
132
+
133
+ class Ecowitt(BaseModel):
134
+ application_key: str | None = None
135
+ api_key: str | None = None
136
+ mac: MacAddress | None = None
137
+
138
+ # HttpUrlString = Annotated[HttpUrl, AfterValidator(lambda v: str(v))]
139
+ realtime_url: HttpUrl = Field(default=HttpUrl("https://api.ecowitt.net/api/v3/device/real_time"))
140
+ device_info_url: HttpUrl = Field(default=HttpUrl("https://api.ecowitt.net/api/v3/device/info"))
141
+
142
+ # @field_validator('mac', mode="before")
143
+ # @classmethod
144
+ # def validate_mac(cls, v):
145
+ # # logger.debug(f"VALIDATE MAC: {v}")
146
+ # if not v:
147
+ # return None
148
+ #
149
+ # return cls.mac_no_colon_to_colon(v)
150
+
151
+
152
+ class Redis(BaseModel):
153
+ host: str = Field(default="127.0.0.1")
154
+ host_in_cluster: Optional[str] = Field(default=None)
155
+ port: int = Field(default=6379)
156
+ port_in_cluster: int = Field(default=6379)
157
+
158
+
159
+ class Google(BaseModel):
160
+ gemini_api_key: str | None = Field(default=None)
161
+
162
+
163
+ class Anthropic(BaseModel):
164
+ anthropic_api_key: str | None = Field(default=None)
165
+
166
+
167
+ class Postgresql(BaseModel):
168
+ host: str = Field(default="127.0.0.1")
169
+ host_in_cluster: Optional[str] = Field(default="postgresql.postgresql.svc")
170
+ username: str = Field(default="postgres")
171
+ password: str = Field(default="empty")
172
+ dbname: str = Field(default="postgres")
173
+ port: int = Field(default=5432)
174
+ port_in_cluster: int = Field(default=5432)
175
+ # url: Optional[PostgresDsn] = Field(default=None)
176
+ url: Optional[str] = Field(default=None)
177
+
178
+
179
+ class Mqtt(BaseModel):
180
+ host: str = Field(default="127.0.0.1")
181
+ port: int = Field(default=1883)
182
+ username: str = Field()
183
+ password: str = Field()
184
+
185
+
186
+ class MqttMessageDefaultMetadata(BaseModel):
187
+ # created_at is not really needed here -> will be added "on-the-fly"
188
+ created_at: None | str = Field(default=None)
189
+ # latitude, longitude, elevation for sensor/actor
190
+ lat: None | float = Field(default=None)
191
+ lon: None | float = Field(default=None)
192
+ ele: None | float = Field(default=None)
193
+
194
+
195
+ class Hydromail(BaseModel):
196
+ smtpip: IPvAnyAddress
197
+ mailfrom: EmailStr
198
+ mailreplyto: EmailStr
199
+ mailsubject_base: str
200
+ mailrecipients_to: List[EmailStr]
201
+ mailrecipients_cc: List[EmailStr]
202
+
203
+
204
+ class Settings(BaseSettings):
205
+ model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(
206
+ populate_by_name=True,
207
+ # env_prefix="TAS_",
208
+ case_sensitive=False,
209
+ extra="ignore", # ignore | forbid | allow
210
+ protected_namespaces=(),
211
+ env_nested_delimiter="__",
212
+ # alias_generator=AliasGenerator(
213
+ # validation_alias=to_camel,
214
+ # serialization_alias=to_pascal,
215
+ # )
216
+ )
217
+
218
+ # emailsettings: EmailSettings
219
+ redis: Redis
220
+ postgresql: Postgresql
221
+ timezone: str = Field(default="Europe/Berlin")
222
+ google: Google
223
+ anthropic: Anthropic
224
+ ecowitt: Ecowitt
225
+ mqtt: Mqtt
226
+ mqtt_message_default_metadata: MqttMessageDefaultMetadata
227
+ netatmo: Netatmo
228
+ hydromail: Hydromail
229
+ mqtt_topics: MqttTopics
230
+
231
+ @classmethod
232
+ def settings_customise_sources(
233
+ cls,
234
+ settings_cls: Type[BaseSettings],
235
+ init_settings: InitSettingsSource, # type: ignore
236
+ env_settings: EnvSettingsSource, # type: ignore
237
+ dotenv_settings: DotEnvSettingsSource, # type: ignore
238
+ file_secret_settings: PydanticBaseSettingsSource,
239
+ ) -> Tuple[PydanticBaseSettingsSource, ...]:
240
+ return init_settings, env_settings, _EffectiveConfigSource(settings_cls)
241
+
242
+
243
+ @lru_cache(maxsize=1)
244
+ def get_settings() -> Settings:
245
+ logger.debug(f"EFFECTIVE CONFIGPATH: {config_path()}")
246
+ logger.debug(f"EFFECTIVE CONFIGLOCALPATH: {config_local_path()}")
247
+ return Settings() # type: ignore[call-arg]
248
+
249
+
250
+ class _LazySettings:
251
+ def __getattr__(self, name: str) -> Any:
252
+ return getattr(get_settings(), name)
253
+
254
+
255
+ settings: Settings = cast(Settings, _LazySettings())
256
+
257
+
258
+ @lru_cache(maxsize=1)
259
+ def get_timezone() -> datetime.tzinfo:
260
+ return pytz.timezone(get_settings().timezone)
261
+
262
+
263
+ def str2bool(v: str | bool) -> bool:
264
+ if not v:
265
+ return False
266
+
267
+ if isinstance(v, bool):
268
+ return v
269
+
270
+ return v.lower() in ("yes", "true", "t", "1")
271
+
272
+
273
+ @cached(cache=TTLCache(maxsize=1, ttl=60))
274
+ def is_in_cluster() -> bool:
275
+ sa: Path = Path("/var/run/secrets/kubernetes.io/serviceaccount")
276
+ if sa.exists() and sa.is_dir():
277
+ return os.getenv("KUBERNETES_SERVICE_HOST") is not None
278
+ return False
279
+
280
+
281
+ def log_settings() -> None:
282
+ logger.info(json.dumps(get_settings().model_dump(by_alias=True), indent=4, sort_keys=False, default=str))
283
+
284
+
285
+ if __name__ == "__main__":
286
+ from somestuff.corestuff import configure_logging
287
+
288
+ configure_logging()
289
+ log_settings()
290
+ logger.info(json.dumps(get_effective_config(), indent=4, sort_keys=False, default=str))
291
+ helper.get_loguru_logger_info()
@@ -0,0 +1,117 @@
1
+ emailsettings:
2
+ privileged_sender: "someone@example.com"
3
+ mailaddress: "mailbox@example.com"
4
+ mailuser: "mailbox@example.com"
5
+ mailpassword: "fumpuslumpus"
6
+ imapserver: "imap.hopefully.not.office365.blargh"
7
+ imapport: 143
8
+ smtpserver: "smtp.hopefully.not.office365.blargh"
9
+ smtpport: 587
10
+ folders:
11
+ old: "WORKED"
12
+ cur: "WORKING"
13
+ rej: "REJECTED"
14
+ err: "FAILED"
15
+ alloweddomains:
16
+ - "onecorp.bizme"
17
+ - "secondcorp.bizme"
18
+
19
+ hydromail:
20
+ smtpip: "127.0.0.1"
21
+ mailfrom: "hydromail@example.com"
22
+ mailreplyto: "hydromail@example.org"
23
+ mailsubject_base: "Regenmessdaten :: Some Where There"
24
+ mailrecipients_to:
25
+ - "otherone@example.org"
26
+ mailrecipients_cc:
27
+ - "someone@example.net"
28
+ - "somehone@example.org"
29
+
30
+
31
+ redis:
32
+ host: "127.0.0.1"
33
+ port: 6379
34
+
35
+ google:
36
+ gemini_api_key: "WOBBLE-DOBBLE-DINGDONG"
37
+
38
+ anthropic:
39
+ anthropic_api_key: "sk-ant-DOBBLE-WOBBLE-DINGDONG"
40
+
41
+ ecowitt:
42
+ application_key: "bluppkey"
43
+ api_key: "blargkey"
44
+ realtime_url: "https://api.ecowitt.net/api/v3/device/real_time"
45
+ device_info_url: "https://api.ecowitt.net/api/v3/device/info"
46
+ mac: "de:ad:be:ef:fe:ed"
47
+
48
+ netatmo:
49
+ username: "someusername"
50
+ password: "somepassword"
51
+ client_id: "someclientid"
52
+ client_secret: "someclientsecret"
53
+ # refresh_token: "somerefreshtoken"
54
+ outdoormodule:
55
+ name: "Außen"
56
+ id: "01:12:34:56:22:11"
57
+ rainmodule:
58
+ name: "RegenModul"
59
+ id: "01:12:34:56:33:22"
60
+
61
+
62
+ postgresql:
63
+ host: "127.0.0.1"
64
+ host_in_cluster: "postgresql.postgresql.svc"
65
+ port: 5438
66
+ port_in_cluster: 5432
67
+ username: "postgres"
68
+ password: "postgrespass"
69
+ dbname: "postgres"
70
+
71
+
72
+
73
+ mqtt:
74
+ username: "MQTT_USERNAME"
75
+ password: "MQTT_PASS"
76
+ host: "MQTT_HOST"
77
+ port: 1883
78
+ # TLS not used/implemented as of now.
79
+
80
+ mqtt_topics:
81
+ ecowitt:
82
+ pressure:
83
+ topic: "ecowitt/pressure"
84
+ subscribe: false
85
+ netatmo:
86
+ temperature:
87
+ topic: "netatmo/temperature"
88
+ subscribe: false
89
+ rainfeed:
90
+ topic: "netatmo/rain"
91
+ subscribe: false
92
+ rainfeed1h:
93
+ topic: "netatmo/rain1h"
94
+ subscribe: false
95
+ rainfeed24h:
96
+ topic: "netatmo/rain24h"
97
+ subscribe: false
98
+ pressurefeed:
99
+ topic: "netatmo/pressure"
100
+ subscribe: false
101
+ wasserstand:
102
+ ma:
103
+ topic: "esp32/esp32_9191919191/ma"
104
+ subscribe: false
105
+ busvoltage:
106
+ topic: "esp32/esp32_9191919191/busvoltage"
107
+ subscribe: false
108
+ wasserstand:
109
+ topic: "nodered/hydrostatics/hydrostatic0/status"
110
+ subscribe: false
111
+
112
+ mqtt_message_default_metadata:
113
+ # latitude, longitude, elevation for sensor/actor
114
+ lat: 1.234567
115
+ lon: 2.345678
116
+ ele: 3.456
117
+
@@ -0,0 +1,141 @@
1
+ import datetime
2
+ import json
3
+ import traceback
4
+ import uuid
5
+ from enum import Enum
6
+ from typing import Any, Dict, List
7
+
8
+
9
+ def get_loguru_logger_info() -> None:
10
+ # deferred import
11
+ from loguru import logger
12
+
13
+ def inspect_loggers() -> List[Dict[str, Any]]:
14
+ """Gibt eine Liste aller konfigurierten Logger-Handler zurück."""
15
+ handlers_info = []
16
+
17
+ lvint_to_lvname: Dict[int, str] = {lvv.no: lvv.name for lvv in logger._core.levels.values()} # type: ignore
18
+
19
+ for handler_id, handler in logger._core.handlers.items(): # type: ignore
20
+ info = {
21
+ "id": handler_id,
22
+ "level": handler._levelno,
23
+ "level_name": lvint_to_lvname[handler._levelno], # handler._level_name,
24
+ "format": handler._formatter,
25
+ "sink": str(handler._sink),
26
+ "filter": handler._filter.__name__ if callable(handler._filter) else str(handler._filter),
27
+ "colorize": getattr(handler, "_colorize", None),
28
+ "serialize": getattr(handler, "_serialize", None),
29
+ }
30
+ handlers_info.append(info)
31
+
32
+ return handlers_info
33
+
34
+ def get_all_filters() -> List[Any]:
35
+ """Gibt alle Filter aller Handler zurück."""
36
+ filters = []
37
+
38
+ for handler_id, handler in logger._core.handlers.items(): # type: ignore
39
+ filter_func = handler._filter
40
+ if filter_func is not None:
41
+ filters.append(
42
+ {
43
+ "handler_id": handler_id,
44
+ "filter": filter_func,
45
+ "filter_name": filter_func.__name__ if callable(filter_func) else str(filter_func),
46
+ }
47
+ )
48
+
49
+ return filters
50
+
51
+ for handler in inspect_loggers():
52
+ logger.info(f"Handler {handler['id']}:")
53
+ logger.info(f" Level: {handler['level_name']} ({handler['level']})")
54
+ logger.info(f" Format: {handler['format']}")
55
+ logger.info(f" Sink: {handler['sink']}")
56
+ logger.info(f" Filter: {handler['filter']}")
57
+ logger.info("")
58
+
59
+ # only filters:
60
+ for f in get_all_filters():
61
+ logger.info(f"Handler {f['handler_id']}: {f['filter_name']}")
62
+
63
+
64
+ class ComplexEncoder(json.JSONEncoder):
65
+ def default(self, obj: Any) -> Any:
66
+ if hasattr(obj, "repr_json"):
67
+ return obj.repr_json()
68
+ elif hasattr(obj, "as_string"):
69
+ return obj.as_string()
70
+ elif isinstance(obj, uuid.UUID):
71
+ return str(obj)
72
+ elif isinstance(obj, datetime.datetime):
73
+ return obj.isoformat() # strftime("%Y-%m-%d %H:%M:%S %Z")
74
+ elif isinstance(obj, datetime.date):
75
+ return obj.strftime("%Y-%m-%d")
76
+ elif isinstance(obj, datetime.timedelta):
77
+ return str(obj)
78
+ elif isinstance(obj, dict) or isinstance(obj, list):
79
+ robj: str = get_pretty_dict_json_no_sort(obj)
80
+ return robj
81
+ else:
82
+ return json.JSONEncoder.default(self, obj)
83
+
84
+
85
+ def print_pretty_dict_json(data: Any, indent: int = 4) -> None:
86
+ from loguru import logger
87
+
88
+ logger.info(json.dumps(data, indent=indent, sort_keys=True, cls=ComplexEncoder, default=str))
89
+
90
+
91
+ def get_pretty_dict_json(data: Any, indent: int = 4) -> str:
92
+ return json.dumps(data, indent=indent, sort_keys=True, cls=ComplexEncoder, default=str)
93
+
94
+
95
+ def get_pretty_dict_json_no_sort(data: Any, indent: int = 4) -> str:
96
+ return json.dumps(data, indent=indent, sort_keys=False, cls=ComplexEncoder, default=str)
97
+
98
+
99
+ def update_deep(base: Dict[str, Any] | List[Any], u: Dict[str, Any] | List[Any]) -> Dict[str, Any] | List[Any]:
100
+ if isinstance(u, dict):
101
+ if not isinstance(base, dict):
102
+ base = {}
103
+
104
+ for k, v in u.items():
105
+ if isinstance(v, dict) or isinstance(v, list):
106
+ base[k] = update_deep(base.get(k, {}), v)
107
+ else:
108
+ base[k] = v
109
+
110
+ elif isinstance(u, list):
111
+ if not isinstance(base, list):
112
+ base = [] # may destroy the existing data if mismatch!!!
113
+
114
+ # Stelle sicher, dass base lang genug ist
115
+ # geht auch kompakter, aber so ist es gut lesbar
116
+ while len(base) < len(u):
117
+ base.append(None)
118
+
119
+ # Stelle sicher, dass base nicht länger ist...
120
+ # geht auch kompakter, aber so ist es gut lesbar
121
+ while len(base) > len(u):
122
+ base.pop()
123
+
124
+ for i, v in enumerate(u):
125
+ if isinstance(v, dict) or isinstance(v, list):
126
+ base[i] = update_deep(base[i] if base[i] is not None else ({} if isinstance(v, dict) else []), v) # type: ignore
127
+ else:
128
+ base[i] = v
129
+
130
+ return base
131
+
132
+
133
+ def get_exception_tb_as_string(exc: Exception) -> str:
134
+ tb1: traceback.TracebackException = traceback.TracebackException.from_exception(exc)
135
+ tbsg = tb1.format()
136
+ tbs = ""
137
+
138
+ for line in tbsg:
139
+ tbs = tbs + "\n" + line
140
+
141
+ return tbs
File without changes