aind-settings-utils 0.0.1__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,8 @@
1
+ [flake8]
2
+ exclude =
3
+ .git,
4
+ __pycache__,
5
+ build,
6
+ .venv,
7
+ venv
8
+ max-complexity = 10
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: Bug report
3
+ about: Create a report to help us improve
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Describe the bug**
11
+ A clear and concise description of what the bug is.
12
+
13
+ **To Reproduce**
14
+ Steps to reproduce the behavior:
15
+ 1. Go to '...'
16
+ 2. Click on '....'
17
+ 3. Scroll down to '....'
18
+ 4. See error
19
+
20
+ **Expected behavior**
21
+ A clear and concise description of what you expected to happen.
22
+
23
+ **Screenshots**
24
+ If applicable, add screenshots to help explain your problem.
25
+
26
+ **Desktop (please complete the following information):**
27
+ - OS: [e.g. iOS]
28
+ - Browser [e.g. chrome, safari]
29
+ - Version [e.g. 22]
30
+
31
+ **Smartphone (please complete the following information):**
32
+ - Device: [e.g. iPhone6]
33
+ - OS: [e.g. iOS8.1]
34
+ - Browser [e.g. stock browser, safari]
35
+ - Version [e.g. 22]
36
+
37
+ **Additional context**
38
+ Add any other context about the problem here.
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Is your feature request related to a problem? Please describe.**
11
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12
+
13
+ **Describe the solution you'd like**
14
+ A clear and concise description of what you want to happen.
15
+
16
+ **Describe alternatives you've considered**
17
+ A clear and concise description of any alternative solutions or features you've considered.
18
+
19
+ **Additional context**
20
+ Add any other context or screenshots about the feature request here.
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: User story
3
+ about: This template provides a basic structure for user story issues.
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ # User story
11
+ As a ..., I want to ..., so I can ...
12
+
13
+ *Ideally, this is in the issue title, but if not, you can put it here. If so, delete this section.*
14
+
15
+ # Acceptance criteria
16
+ - [ ] This is something that can be verified to show that this user story is satisfied.
17
+
18
+ # Sprint Ready Checklist
19
+ - [ ] 1. Acceptance criteria defined
20
+ - [ ] 2. Team understands acceptance criteria
21
+ - [ ] 3. Team has defined solution / steps to satisfy acceptance criteria
22
+ - [ ] 4. Acceptance criteria is verifiable / testable
23
+ - [ ] 5. External / 3rd Party dependencies identified
24
+ - [ ] 6. Ticket is prioritized and sized
25
+
26
+ # Notes
27
+ *Add any helpful notes here.*
@@ -0,0 +1,84 @@
1
+ name: Tag and publish
2
+ on:
3
+ push:
4
+ branches:
5
+ - main
6
+ jobs:
7
+ update_badges:
8
+ runs-on: ubuntu-latest
9
+ continue-on-error: true
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ with:
13
+ ref: ${{ env.DEFAULT_BRANCH }}
14
+ fetch-depth: 0
15
+ token: ${{ secrets.SERVICE_TOKEN }}
16
+ - name: Set up Python 3.10
17
+ uses: actions/setup-python@v5
18
+ with:
19
+ python-version: '3.10'
20
+ - name: Install dependencies
21
+ run: |
22
+ python -m pip install -e .[dev] --no-cache-dir
23
+ - name: Get Python version and Update README.md
24
+ run: |
25
+ python_version=$(grep "requires-python" pyproject.toml | grep -o ">=[^\"]*")
26
+ python_badge=$(grep -o 'python-[^)]*' README.md)
27
+ new_python_badge="python-$python_version-blue?logo=python"
28
+ sed -i "s/$python_badge/$new_python_badge/g" README.md
29
+ - name: Get interrogate values and Update README.md
30
+ run: |
31
+ interrogate_val=$(interrogate . | grep -o 'actual: [0-9]*\.[0-9]*' | awk '{print $2}')
32
+ interrogate_badge=$(grep -o 'interrogate-[^)]*' README.md)
33
+ if (( $(echo "$interrogate_val >= 90.00" | bc -l) )); then
34
+ new_interrogate_badge="interrogate-$interrogate_val%25-brightgreen"
35
+ elif (( $(echo "$interrogate_val < 80.00" | bc -l) )); then
36
+ new_interrogate_badge="interrogate-$interrogate_val%25-red"
37
+ else
38
+ new_interrogate_badge="interrogate-$interrogate_val%25-yellow"
39
+ fi
40
+ sed -i "s/$interrogate_badge/$new_interrogate_badge/g" README.md
41
+ - name: Get Coverage values and Update README.md
42
+ run: |
43
+ coverage run -m unittest discover
44
+ coverage_val=$(coverage report | grep "^TOTAL" | grep -o '[0-9]\+%' | grep -o '[0-9]\+')
45
+ coverage_badge=$(grep -o "coverage-[^?]*" README.md)
46
+ if (( $(echo "$coverage_val >= 90.00" | bc -l) )); then
47
+ new_coverage_badge="coverage-$coverage_val%25-brightgreen"
48
+ elif (( $(echo "$coverage_val < 80.00" | bc -l) )); then
49
+ new_coverage_badge="coverage-$coverage_val%25-red"
50
+ else
51
+ new_coverage_badge="coverage-$coverage_val%25-yellow"
52
+ fi
53
+ sed -i "s/$coverage_badge/$new_coverage_badge/g" README.md
54
+ - name: Commit changes
55
+ uses: EndBug/add-and-commit@v9
56
+ with:
57
+ default_author: github_actions
58
+ message: "ci: update badges [skip actions]"
59
+ add: '["README.md"]'
60
+ tag:
61
+ needs: update_badges
62
+ uses: AllenNeuralDynamics/aind-github-actions/.github/workflows/tag.yml@main
63
+ secrets:
64
+ SERVICE_TOKEN: ${{ secrets.SERVICE_TOKEN }}
65
+ publish:
66
+ needs: tag
67
+ runs-on: ubuntu-latest
68
+ steps:
69
+ - uses: actions/checkout@v4
70
+ - name: Pull latest changes
71
+ run: git pull origin main
72
+ - name: Set up Python 3.10
73
+ uses: actions/setup-python@v5
74
+ with:
75
+ python-version: '3.10'
76
+ - name: Install dependencies
77
+ run: |
78
+ pip install --upgrade setuptools wheel twine build
79
+ python -m build
80
+ twine check dist/*
81
+ - name: Publish on PyPI
82
+ uses: pypa/gh-action-pypi-publish@release/v1
83
+ with:
84
+ password: ${{ secrets.AIND_PYPI_TOKEN }}
@@ -0,0 +1,26 @@
1
+ name: Lint and run tests
2
+
3
+ on:
4
+ pull_request:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ ci:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12' ]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - name: Set up Python ${{ matrix.python-version }}
17
+ uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install dependencies
21
+ run: |
22
+ python -m pip install -e .[dev]
23
+ - name: Run linter checks
24
+ run: flake8 . && interrogate --verbose .
25
+ - name: Run tests and coverage
26
+ run: coverage run -m unittest discover && coverage report
@@ -0,0 +1,139 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+
131
+ # PyCharm
132
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
133
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
134
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
135
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
136
+ .idea/
137
+
138
+ # MacOs
139
+ **/.DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Allen Institute for Neural Dynamics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: aind-settings-utils
3
+ Version: 0.0.1
4
+ Summary: Generated from aind-library-template
5
+ Author: Allen Institute for Neural Dynamics
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: boto3
12
+ Requires-Dist: pydantic-settings>=2.0
13
+ Requires-Dist: pydantic>=2.0
14
+ Provides-Extra: dev
15
+ Requires-Dist: black; extra == "dev"
16
+ Requires-Dist: coverage; extra == "dev"
17
+ Requires-Dist: flake8; extra == "dev"
18
+ Requires-Dist: interrogate; extra == "dev"
19
+ Requires-Dist: isort; extra == "dev"
20
+ Requires-Dist: Sphinx; extra == "dev"
21
+ Requires-Dist: furo; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # aind-settings-utils
25
+
26
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
27
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
28
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
29
+ ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
30
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?logo=codecov)
31
+ ![Python](https://img.shields.io/badge/python->=3.8-blue?logo=python)
32
+
33
+
34
+
35
+ ## Usage
36
+
37
+ This package is intended to be installed as a utility package alongside apps.
38
+
39
+ ### App settings store as a json file in AWS Parameter store.
40
+
41
+ AWS credentials are handled by boto3.
42
+
43
+ If you have a parameter in Parameter store under:
44
+ ```bash
45
+ /dev/my_param
46
+ ```
47
+
48
+ with contents:
49
+ ```
50
+ {"app_name": "my app", "app_arg1": 3}
51
+ ```
52
+
53
+ then you can pull that information into a settings class like:
54
+ ```python
55
+ from aind_settings_utils.aws import (
56
+ ParameterStoreAppBaseSettings,
57
+ )
58
+
59
+ class ExampleSettings(ParameterStoreAppBaseSettings):
60
+
61
+ app_name: str
62
+ app_arg1: int
63
+
64
+ model_config = {
65
+ "aws_param_store_name": "/dev/my_param", # Or pull it from an env var
66
+ "case_sensitive": False,
67
+ }
68
+
69
+ ```
70
+
71
+ You can then import and create an `ExampleSettings` class:
72
+
73
+ ```python
74
+ example_settings = ExampleSettings()
75
+ print(example_settings.app_name)
76
+ print(example_settings.app_arg1)
77
+ ```
78
+
79
+
80
+ ## Contributing
81
+
82
+ Clone this repo and install the development packages locally:
83
+ ```bash
84
+ pip install -e ".[dev]"
85
+ ```
86
+
87
+ ### Linters and testing
88
+
89
+ There are several libraries used to run linters, check documentation, and run tests.
90
+
91
+ - Please test your changes using the **coverage** library, which will run the tests and log a coverage report:
92
+
93
+ ```bash
94
+ coverage run -m unittest discover && coverage report
95
+ ```
96
+
97
+ - Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
98
+
99
+ ```bash
100
+ interrogate .
101
+ ```
102
+
103
+ - Use **flake8** to check that code is up to standards (no unused imports, etc.):
104
+ ```bash
105
+ flake8 .
106
+ ```
107
+
108
+ - Use **black** to automatically format the code into PEP standards:
109
+ ```bash
110
+ black .
111
+ ```
112
+
113
+ - Use **isort** to automatically sort import statements:
114
+ ```bash
115
+ isort .
116
+ ```
117
+
118
+ ### Pull requests
119
+
120
+ For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern:
121
+ ```text
122
+ <type>(<scope>): <short summary>
123
+ ```
124
+
125
+ where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
126
+
127
+ - **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
128
+ - **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
129
+ - **docs**: Documentation only changes
130
+ - **feat**: A new feature
131
+ - **fix**: A bugfix
132
+ - **perf**: A code change that improves performance
133
+ - **refactor**: A code change that neither fixes a bug nor adds a feature
134
+ - **test**: Adding missing tests or correcting existing tests
135
+
136
+ ### Semantic Release
137
+
138
+ The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration):
139
+
140
+ | Commit message | Release type |
141
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
142
+ | `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release |
143
+ | `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
144
+ | `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
@@ -0,0 +1,121 @@
1
+ # aind-settings-utils
2
+
3
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
4
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
5
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
6
+ ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
7
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?logo=codecov)
8
+ ![Python](https://img.shields.io/badge/python->=3.8-blue?logo=python)
9
+
10
+
11
+
12
+ ## Usage
13
+
14
+ This package is intended to be installed as a utility package alongside apps.
15
+
16
+ ### App settings store as a json file in AWS Parameter store.
17
+
18
+ AWS credentials are handled by boto3.
19
+
20
+ If you have a parameter in Parameter store under:
21
+ ```bash
22
+ /dev/my_param
23
+ ```
24
+
25
+ with contents:
26
+ ```
27
+ {"app_name": "my app", "app_arg1": 3}
28
+ ```
29
+
30
+ then you can pull that information into a settings class like:
31
+ ```python
32
+ from aind_settings_utils.aws import (
33
+ ParameterStoreAppBaseSettings,
34
+ )
35
+
36
+ class ExampleSettings(ParameterStoreAppBaseSettings):
37
+
38
+ app_name: str
39
+ app_arg1: int
40
+
41
+ model_config = {
42
+ "aws_param_store_name": "/dev/my_param", # Or pull it from an env var
43
+ "case_sensitive": False,
44
+ }
45
+
46
+ ```
47
+
48
+ You can then import and create an `ExampleSettings` class:
49
+
50
+ ```python
51
+ example_settings = ExampleSettings()
52
+ print(example_settings.app_name)
53
+ print(example_settings.app_arg1)
54
+ ```
55
+
56
+
57
+ ## Contributing
58
+
59
+ Clone this repo and install the development packages locally:
60
+ ```bash
61
+ pip install -e ".[dev]"
62
+ ```
63
+
64
+ ### Linters and testing
65
+
66
+ There are several libraries used to run linters, check documentation, and run tests.
67
+
68
+ - Please test your changes using the **coverage** library, which will run the tests and log a coverage report:
69
+
70
+ ```bash
71
+ coverage run -m unittest discover && coverage report
72
+ ```
73
+
74
+ - Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
75
+
76
+ ```bash
77
+ interrogate .
78
+ ```
79
+
80
+ - Use **flake8** to check that code is up to standards (no unused imports, etc.):
81
+ ```bash
82
+ flake8 .
83
+ ```
84
+
85
+ - Use **black** to automatically format the code into PEP standards:
86
+ ```bash
87
+ black .
88
+ ```
89
+
90
+ - Use **isort** to automatically sort import statements:
91
+ ```bash
92
+ isort .
93
+ ```
94
+
95
+ ### Pull requests
96
+
97
+ For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern:
98
+ ```text
99
+ <type>(<scope>): <short summary>
100
+ ```
101
+
102
+ where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
103
+
104
+ - **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
105
+ - **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
106
+ - **docs**: Documentation only changes
107
+ - **feat**: A new feature
108
+ - **fix**: A bugfix
109
+ - **perf**: A code change that improves performance
110
+ - **refactor**: A code change that neither fixes a bug nor adds a feature
111
+ - **test**: Adding missing tests or correcting existing tests
112
+
113
+ ### Semantic Release
114
+
115
+ The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration):
116
+
117
+ | Commit message | Release type |
118
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
119
+ | `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release |
120
+ | `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
121
+ | `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
@@ -0,0 +1,82 @@
1
+ [build-system]
2
+ requires = ["setuptools", "setuptools-scm"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "aind-settings-utils"
7
+ description = "Generated from aind-library-template"
8
+ license = {text = "MIT"}
9
+ requires-python = ">=3.8"
10
+ authors = [
11
+ {name = "Allen Institute for Neural Dynamics"}
12
+ ]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3"
15
+ ]
16
+ readme = "README.md"
17
+ dynamic = ["version"]
18
+
19
+ dependencies = [
20
+ 'boto3',
21
+ 'pydantic-settings>=2.0',
22
+ 'pydantic>=2.0',
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = [
27
+ 'black',
28
+ 'coverage',
29
+ 'flake8',
30
+ 'interrogate',
31
+ 'isort',
32
+ 'Sphinx',
33
+ 'furo'
34
+ ]
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.dynamic]
40
+ version = {attr = "aind_settings_utils.__version__"}
41
+
42
+ [tool.black]
43
+ line-length = 79
44
+ target_version = ['py310']
45
+ exclude = '''
46
+
47
+ (
48
+ /(
49
+ \.eggs # exclude a few common directories in the
50
+ | \.git # root of the project
51
+ | \.hg
52
+ | \.mypy_cache
53
+ | \.tox
54
+ | \.venv
55
+ | _build
56
+ | build
57
+ | dist
58
+ )/
59
+ | .gitignore
60
+ )
61
+ '''
62
+
63
+ [tool.coverage.run]
64
+ omit = ["*__init__*"]
65
+ source = ["aind_settings_utils", "tests"]
66
+
67
+ [tool.coverage.report]
68
+ exclude_lines = [
69
+ "if __name__ == .__main__.:",
70
+ "^from .* import .*",
71
+ "^import .*",
72
+ "pragma: no cover"
73
+ ]
74
+ fail_under = 100
75
+
76
+ [tool.isort]
77
+ line_length = 79
78
+ profile = "black"
79
+
80
+ [tool.interrogate]
81
+ exclude = ["setup.py", "docs", "build"]
82
+ fail-under = 100
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from setuptools import setup
2
+
3
+ if __name__ == "__main__":
4
+ setup()
@@ -0,0 +1,3 @@
1
+ """Init package"""
2
+
3
+ __version__ = "0.0.1"
@@ -0,0 +1,178 @@
1
+ """Module to handle custom settings pulled from AWS"""
2
+
3
+ import functools
4
+ import json
5
+ import logging
6
+ from typing import Any, Dict, Optional, Tuple, Type
7
+
8
+ import boto3
9
+ from pydantic.fields import FieldInfo
10
+ from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
11
+ from pydantic_settings.sources import PydanticBaseEnvSettingsSource
12
+
13
+
14
+ class AWSParamStoreAppSource(PydanticBaseEnvSettingsSource):
15
+ """
16
+ Custom source that will pull settings defined in a json file hosted on
17
+ AWS Parameter Store.
18
+ """
19
+
20
+ # noinspection PyUnresolvedReferences
21
+ def __init__(
22
+ self,
23
+ settings_cls: Type[BaseSettings],
24
+ aws_param_store_name: Optional[str] = None,
25
+ case_sensitive: Optional[bool] = None,
26
+ env_prefix: Optional[str] = None,
27
+ env_ignore_empty: Optional[bool] = None,
28
+ env_parse_none_str: Optional[str] = None,
29
+ ) -> None:
30
+ """Class constructor"""
31
+ super().__init__(
32
+ settings_cls,
33
+ case_sensitive,
34
+ env_prefix,
35
+ env_ignore_empty,
36
+ env_parse_none_str,
37
+ )
38
+ self.aws_param_store_name = (
39
+ aws_param_store_name
40
+ if aws_param_store_name is not None
41
+ else self.config.get("aws_param_store_name")
42
+ )
43
+
44
+ @staticmethod
45
+ def _get_parameter(parameter_name: str) -> Dict[str, Any]:
46
+ """
47
+ Retrieves a parameter file from AWS Param Store
48
+
49
+ Parameters
50
+ ----------
51
+ parameter_name : str
52
+ Parameter name as stored in AWS Param Store
53
+
54
+ Returns
55
+ -------
56
+ Dict[str, Any]
57
+ Contents of the secret
58
+
59
+ """
60
+ client = boto3.client("ssm")
61
+ try:
62
+ response = client.get_parameter(
63
+ Name=parameter_name, WithDecryption=True
64
+ )
65
+ finally:
66
+ client.close()
67
+ return json.loads(response["Parameter"]["Value"])
68
+
69
+ @functools.cached_property
70
+ def _json_contents(self):
71
+ """
72
+ Cache contents to avoid re-downloading.
73
+ """
74
+ contents_from_aws = self._get_parameter(
75
+ self.config.get("aws_param_store_name")
76
+ )
77
+ return contents_from_aws
78
+
79
+ @classmethod
80
+ def find_case_param(
81
+ cls, json_contents: dict, param_name: str, case_sensitive: bool
82
+ ) -> Optional[str]:
83
+ """
84
+ Find a parameter from a json dictionary pulled from aws
85
+
86
+ Parameters
87
+ ----------
88
+ json_contents: dict
89
+ param_name: str
90
+ case_sensitive: bool
91
+ Whether to search for param name case sensitively.
92
+
93
+ Returns
94
+ -------
95
+ str | None
96
+ The parameter pulled from the json object or None if not found.
97
+ """
98
+
99
+ if json_contents.get(param_name) is not None:
100
+ return json_contents.get(param_name)
101
+ elif (
102
+ not case_sensitive
103
+ and json_contents.get(param_name.upper()) is not None
104
+ ):
105
+ return json_contents.get(param_name.upper())
106
+ else:
107
+ return None
108
+
109
+ def get_field_value(
110
+ self, field: FieldInfo, field_name: str
111
+ ) -> Tuple[Any, str, bool]:
112
+ """
113
+ Gets the value for field from secret file and a flag to determine
114
+ whether value is complex.
115
+
116
+ Parameters
117
+ ----------
118
+ field: FieldInfo
119
+ field_name: str
120
+
121
+ Returns
122
+ -------
123
+ Tuple[Any, str, bool]
124
+ A tuple contains the key, value if the file exists otherwise `None`,
125
+ and a flag to determine whether the value is complex.
126
+ """
127
+ param = None
128
+ field_key = ""
129
+ value_is_complex = False
130
+ for field_key, env_name, value_is_complex in self._extract_field_info(
131
+ field, field_name
132
+ ):
133
+ param = self.find_case_param(
134
+ self._json_contents, env_name, self.case_sensitive
135
+ )
136
+ if param:
137
+ return param, field_key, value_is_complex
138
+ else:
139
+ logging.debug(f"param not found {field_key}")
140
+
141
+ return param, field_key, value_is_complex
142
+
143
+
144
+ class ParameterStoreAppBaseSettings(BaseSettings):
145
+ """
146
+ Custom Settings class to handle app settings stored as a json file hosted
147
+ on AWS Parameter Store.
148
+ """
149
+
150
+ @classmethod
151
+ def settings_customise_sources(
152
+ cls,
153
+ settings_cls: Type[BaseSettings],
154
+ init_settings: PydanticBaseSettingsSource,
155
+ env_settings: PydanticBaseSettingsSource,
156
+ dotenv_settings: PydanticBaseSettingsSource,
157
+ file_secret_settings: PydanticBaseSettingsSource,
158
+ ) -> Tuple[PydanticBaseSettingsSource, ...]:
159
+ """
160
+ If the param store name is not set, then use standard fallbacks. If
161
+ param store name is set, then prioritize the values stored there.
162
+ """
163
+
164
+ if settings_cls.model_config.get("aws_param_store_name") is None:
165
+ return (
166
+ init_settings,
167
+ env_settings,
168
+ dotenv_settings,
169
+ file_secret_settings,
170
+ )
171
+ else:
172
+ return (
173
+ init_settings,
174
+ AWSParamStoreAppSource(settings_cls),
175
+ env_settings,
176
+ dotenv_settings,
177
+ file_secret_settings,
178
+ )
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: aind-settings-utils
3
+ Version: 0.0.1
4
+ Summary: Generated from aind-library-template
5
+ Author: Allen Institute for Neural Dynamics
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: boto3
12
+ Requires-Dist: pydantic-settings>=2.0
13
+ Requires-Dist: pydantic>=2.0
14
+ Provides-Extra: dev
15
+ Requires-Dist: black; extra == "dev"
16
+ Requires-Dist: coverage; extra == "dev"
17
+ Requires-Dist: flake8; extra == "dev"
18
+ Requires-Dist: interrogate; extra == "dev"
19
+ Requires-Dist: isort; extra == "dev"
20
+ Requires-Dist: Sphinx; extra == "dev"
21
+ Requires-Dist: furo; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # aind-settings-utils
25
+
26
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
27
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
28
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
29
+ ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
30
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?logo=codecov)
31
+ ![Python](https://img.shields.io/badge/python->=3.8-blue?logo=python)
32
+
33
+
34
+
35
+ ## Usage
36
+
37
+ This package is intended to be installed as a utility package alongside apps.
38
+
39
+ ### App settings store as a json file in AWS Parameter store.
40
+
41
+ AWS credentials are handled by boto3.
42
+
43
+ If you have a parameter in Parameter store under:
44
+ ```bash
45
+ /dev/my_param
46
+ ```
47
+
48
+ with contents:
49
+ ```
50
+ {"app_name": "my app", "app_arg1": 3}
51
+ ```
52
+
53
+ then you can pull that information into a settings class like:
54
+ ```python
55
+ from aind_settings_utils.aws import (
56
+ ParameterStoreAppBaseSettings,
57
+ )
58
+
59
+ class ExampleSettings(ParameterStoreAppBaseSettings):
60
+
61
+ app_name: str
62
+ app_arg1: int
63
+
64
+ model_config = {
65
+ "aws_param_store_name": "/dev/my_param", # Or pull it from an env var
66
+ "case_sensitive": False,
67
+ }
68
+
69
+ ```
70
+
71
+ You can then import and create an `ExampleSettings` class:
72
+
73
+ ```python
74
+ example_settings = ExampleSettings()
75
+ print(example_settings.app_name)
76
+ print(example_settings.app_arg1)
77
+ ```
78
+
79
+
80
+ ## Contributing
81
+
82
+ Clone this repo and install the development packages locally:
83
+ ```bash
84
+ pip install -e ".[dev]"
85
+ ```
86
+
87
+ ### Linters and testing
88
+
89
+ There are several libraries used to run linters, check documentation, and run tests.
90
+
91
+ - Please test your changes using the **coverage** library, which will run the tests and log a coverage report:
92
+
93
+ ```bash
94
+ coverage run -m unittest discover && coverage report
95
+ ```
96
+
97
+ - Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
98
+
99
+ ```bash
100
+ interrogate .
101
+ ```
102
+
103
+ - Use **flake8** to check that code is up to standards (no unused imports, etc.):
104
+ ```bash
105
+ flake8 .
106
+ ```
107
+
108
+ - Use **black** to automatically format the code into PEP standards:
109
+ ```bash
110
+ black .
111
+ ```
112
+
113
+ - Use **isort** to automatically sort import statements:
114
+ ```bash
115
+ isort .
116
+ ```
117
+
118
+ ### Pull requests
119
+
120
+ For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern:
121
+ ```text
122
+ <type>(<scope>): <short summary>
123
+ ```
124
+
125
+ where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
126
+
127
+ - **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
128
+ - **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
129
+ - **docs**: Documentation only changes
130
+ - **feat**: A new feature
131
+ - **fix**: A bugfix
132
+ - **perf**: A code change that improves performance
133
+ - **refactor**: A code change that neither fixes a bug nor adds a feature
134
+ - **test**: Adding missing tests or correcting existing tests
135
+
136
+ ### Semantic Release
137
+
138
+ The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration):
139
+
140
+ | Commit message | Release type |
141
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
142
+ | `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release |
143
+ | `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
144
+ | `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
@@ -0,0 +1,20 @@
1
+ .flake8
2
+ .gitignore
3
+ LICENSE
4
+ README.md
5
+ pyproject.toml
6
+ setup.py
7
+ .github/ISSUE_TEMPLATE/bug_report.md
8
+ .github/ISSUE_TEMPLATE/feature_request.md
9
+ .github/ISSUE_TEMPLATE/user-story.md
10
+ .github/workflows/tag_and_publish.yml
11
+ .github/workflows/test_and_lint.yml
12
+ src/aind_settings_utils/__init__.py
13
+ src/aind_settings_utils/aws.py
14
+ src/aind_settings_utils.egg-info/PKG-INFO
15
+ src/aind_settings_utils.egg-info/SOURCES.txt
16
+ src/aind_settings_utils.egg-info/dependency_links.txt
17
+ src/aind_settings_utils.egg-info/requires.txt
18
+ src/aind_settings_utils.egg-info/top_level.txt
19
+ tests/__init__.py
20
+ tests/test_aws.py
@@ -0,0 +1,12 @@
1
+ boto3
2
+ pydantic-settings>=2.0
3
+ pydantic>=2.0
4
+
5
+ [dev]
6
+ black
7
+ coverage
8
+ flake8
9
+ interrogate
10
+ isort
11
+ Sphinx
12
+ furo
@@ -0,0 +1 @@
1
+ aind_settings_utils
@@ -0,0 +1 @@
1
+ """Testing library"""
@@ -0,0 +1,137 @@
1
+ """Module to test custom settings"""
2
+
3
+ import unittest
4
+ from unittest.mock import MagicMock, PropertyMock, patch
5
+
6
+ from aind_settings_utils.aws import (
7
+ AWSParamStoreAppSource,
8
+ ParameterStoreAppBaseSettings,
9
+ )
10
+
11
+
12
+ class ExampleSettings(ParameterStoreAppBaseSettings):
13
+ """Example settings class for testing"""
14
+
15
+ my_secret: str
16
+
17
+ model_config = {
18
+ "aws_param_store_name": "example-name",
19
+ "case_sensitive": False,
20
+ }
21
+
22
+
23
+ class TestAWSParamStoreSource(unittest.TestCase):
24
+ """Test AWSParamStoreAppSource class"""
25
+
26
+ @patch("aind_settings_utils.aws.boto3.client")
27
+ def test_get_parameter(self, mock_boto_client: MagicMock):
28
+ """Tests that parameter is retrieved as expected"""
29
+ # Mock response
30
+ mock_ssm = MagicMock()
31
+ mock_ssm.get_parameter.return_value = {
32
+ "Parameter": {"Value": '{"my_secret": "secret_value"}'}
33
+ }
34
+ mock_boto_client.return_value = mock_ssm
35
+
36
+ result = AWSParamStoreAppSource._get_parameter("example-name")
37
+ self.assertEqual(result, {"my_secret": "secret_value"})
38
+ mock_ssm.get_parameter.assert_called_once_with(
39
+ Name="example-name", WithDecryption=True
40
+ )
41
+ mock_ssm.close.assert_called_once()
42
+
43
+ def test_find_case_param(self):
44
+ """Tests that correct parameter is found in json dictionary"""
45
+
46
+ json_contents = {"keyOne": "value1", "KEYTWO": "value2"}
47
+ result1 = AWSParamStoreAppSource.find_case_param(
48
+ json_contents, "keyOne", case_sensitive=False
49
+ )
50
+ result2 = AWSParamStoreAppSource.find_case_param(
51
+ json_contents, "keytwo", case_sensitive=False
52
+ )
53
+ result3 = AWSParamStoreAppSource.find_case_param(
54
+ json_contents, "keytwo", case_sensitive=True
55
+ )
56
+
57
+ self.assertEqual(result1, "value1")
58
+ self.assertEqual(result2, "value2")
59
+ self.assertIsNone(result3)
60
+
61
+ @patch("aind_settings_utils.aws.boto3.client")
62
+ def test_get_field_value_success(self, mock_boto_client: MagicMock):
63
+ """Tests that field value is retrieved successfully"""
64
+
65
+ mock_ssm = MagicMock()
66
+ mock_ssm.get_parameter.return_value = {
67
+ "Parameter": {"Value": '{"MY_SECRET": "top_secret"}'}
68
+ }
69
+ mock_boto_client.return_value = mock_ssm
70
+ source = AWSParamStoreAppSource(
71
+ ExampleSettings, aws_param_store_name="example-store-name"
72
+ )
73
+ field = ExampleSettings.model_fields["my_secret"]
74
+
75
+ value, key, is_complex = source.get_field_value(field, "my_secret")
76
+ self.assertEqual(value, "top_secret")
77
+ self.assertEqual(key, "my_secret")
78
+ self.assertFalse(is_complex)
79
+
80
+ @patch.object(
81
+ AWSParamStoreAppSource, "_json_contents", new_callable=PropertyMock
82
+ )
83
+ def test_get_field_value_failure(self, mock_json_contents: MagicMock):
84
+ """Tests that field value is not retrieved successfully"""
85
+
86
+ mock_json_contents.return_value = {}
87
+ source = AWSParamStoreAppSource(
88
+ ExampleSettings, aws_param_store_name="example-store-name"
89
+ )
90
+ field = ExampleSettings.model_fields["my_secret"]
91
+
92
+ value, key, is_complex = source.get_field_value(field, "my_secret")
93
+ self.assertIsNone(value)
94
+ self.assertEqual(key, "my_secret")
95
+ self.assertFalse(is_complex)
96
+
97
+
98
+ class TestParameterStoreAppBaseSettings(unittest.TestCase):
99
+ """Test ParameterStoreBaseSettings class"""
100
+
101
+ def test_settings_customise_sources_with_param_store(self):
102
+ """Tests that sources are customised correctly"""
103
+ init = MagicMock()
104
+ env = MagicMock()
105
+ dotenv = MagicMock()
106
+ secret = MagicMock()
107
+ sources = ParameterStoreAppBaseSettings.settings_customise_sources(
108
+ settings_cls=ExampleSettings,
109
+ init_settings=init,
110
+ env_settings=env,
111
+ dotenv_settings=dotenv,
112
+ file_secret_settings=secret,
113
+ )
114
+ self.assertIsInstance(sources[1], AWSParamStoreAppSource)
115
+
116
+ def test_settings_customise_sources_without_param_store(self):
117
+ """Tests that sources are customised correctly"""
118
+
119
+ class NoParamSettings(ParameterStoreAppBaseSettings):
120
+ """Example settings class for testing no param store"""
121
+
122
+ model_config = {}
123
+
124
+ init = MagicMock()
125
+ env = MagicMock()
126
+ dotenv = MagicMock()
127
+ secret = MagicMock()
128
+
129
+ sources = NoParamSettings.settings_customise_sources(
130
+ NoParamSettings, init, env, dotenv, secret
131
+ )
132
+ self.assertEqual(sources[0], init)
133
+ self.assertEqual(len(sources), 4)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ unittest.main()