ashwelness-utils 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 @@
1
+ @roma-ash
@@ -0,0 +1,22 @@
1
+ name: Publish to PyPi
2
+
3
+ on:
4
+ workflow_call:
5
+
6
+ jobs:
7
+ publish:
8
+ runs-on: ubuntu-latest
9
+ name: Publish
10
+ steps:
11
+ - uses: actions/checkout@v3
12
+ - uses: actions/setup-python@v4
13
+ with:
14
+ python-version: "3.11"
15
+ - name: Install uv
16
+ uses: astral-sh/setup-uv@v5
17
+ - name: Build project for distribution
18
+ run: uv build
19
+ - name: Publish to PyPI
20
+ env:
21
+ UV_PUBLISH_TOKEN: ${{ secrets.PYPI_TOKEN }}
22
+ run: uv publish
@@ -0,0 +1,11 @@
1
+ name: Pull Request Pipeline
2
+ on:
3
+ pull_request:
4
+
5
+ jobs:
6
+ validation:
7
+ name: Code Validation
8
+ uses: './.github/workflows/validate_code.yml'
9
+ tests:
10
+ name: Tests
11
+ uses: './.github/workflows/tests.yml'
@@ -0,0 +1,11 @@
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ name: Publish
10
+ uses: './.github/workflows/publish.yaml'
11
+ secrets: inherit
@@ -0,0 +1,35 @@
1
+ name: Run Project Unit Tests
2
+
3
+ on:
4
+ workflow_call:
5
+
6
+ jobs:
7
+ unitTests:
8
+ runs-on: ubuntu-latest
9
+ name: Unit Tests
10
+ env:
11
+ COVERAGE_TOTAL: 90
12
+ PULL_NUMBER: ${{ github.event.pull_request.number }}
13
+ PYTEST_ROOT_DIR: tests
14
+ OMIT_LIST: tests/*
15
+ COMMIT_URL: "https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}/commits/${{ github.event.after }}"
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: 3.11.4
21
+ - id: run-tests-pr
22
+ uses: dima-engineer/pytest-reporter@v4
23
+ with:
24
+ pytest-tests-dir: ${{ env.PYTEST_ROOT_DIR }}
25
+ cov-omit-list: ${{ env.OMIT_LIST }}
26
+ cov-threshold-total: ${{ env.COVERAGE_TOTAL }}
27
+ uv-version: 0.5.29
28
+ - name: Generate XML coverage report
29
+ run: |
30
+ coverage xml
31
+ - name: Upload coverage report
32
+ uses: actions/upload-artifact@v4
33
+ with:
34
+ name: coverage
35
+ path: coverage.xml
@@ -0,0 +1,24 @@
1
+ name: Run code validation
2
+
3
+ on:
4
+ workflow_call:
5
+
6
+ jobs:
7
+ validation:
8
+ runs-on: ubuntu-latest
9
+ name: Validation Checks
10
+ steps:
11
+ - uses: actions/checkout@v3
12
+ - uses: actions/setup-python@v4
13
+ with:
14
+ python-version: "3.11"
15
+ - name: Install uv
16
+ uses: astral-sh/setup-uv@v5
17
+ - name: Install the project
18
+ run: uv sync --all-extras --dev
19
+ - name: Install Lets
20
+ uses: lets-cli/lets-action@v1.1
21
+ with:
22
+ version: latest
23
+ - name: Run Validation
24
+ run: lets val
@@ -0,0 +1,162 @@
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
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
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
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ .idea/
156
+ .python-version
157
+ mysql/
158
+ log/
159
+ .ruff_cache/
160
+ .lets/
161
+ .DS_Store
162
+ Thumbs.db
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: ashwelness-utils
3
+ Version: 0.1.0
4
+ Summary: Python library containing common utilities used across various ASH projects.
5
+ Author-email: Shakun Raman <shakunroman@gmail.com>
6
+ Keywords: fastapi,middleware,security,utilities
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: fastapi>=0.115.7
9
+ Requires-Dist: httpx>=0.28.1
10
+ Requires-Dist: loguru>=0.7.3
11
+ Requires-Dist: pytest-coverage>=0.0
12
+ Requires-Dist: secweb>=1.18.1
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ash-utils
16
+
17
+ Python library containing common utilities used across various ASH projects.
18
+
19
+ ## Features
20
+
21
+ 1. **CatchUnexpectedExceptionsMiddleware** - Global exception handler for unexpected errors
22
+ 2. **RequestIDMiddleware** - Request ID tracking for improved logging and tracing
23
+ 3. **BaseApi** - Base HTTP client with built-in error handling and request ID propagation
24
+ 4. **configure_security_headers** - Function provides a pre-configured security header setup for FastAPI applications following security best practices.
25
+
26
+ ## Installation
27
+
28
+ ### PyPi
29
+
30
+ ```shell
31
+ pip install ashwelness-utils
32
+
33
+ # OR
34
+
35
+ poetry add ashwelness-utils
36
+ ```
37
+
38
+ ### From github
39
+ In order to install Ash DAL directly from GitHub repository, run:
40
+ ```shell
41
+ pip install git+https://github.com/meetash/ash-utils.git@main
42
+
43
+ # OR
44
+
45
+ poetry add git+https://github.com/meetash/ash-utils.git@main
46
+ ```
47
+
48
+ ### Usage
49
+ 1. CatchUnexpectedExceptionsMiddleware
50
+
51
+ *Purpose:* Catch all unexpected exceptions and return a standardized error response.
52
+
53
+ ```python
54
+ from fastapi import FastAPI
55
+ from ash_utils.middlewares import CatchUnexpectedExceptionsMiddleware
56
+
57
+ app = FastAPI()
58
+
59
+ # Add middleware with custom error message
60
+ app.add_middleware(
61
+ CatchUnexpectedExceptionsMiddleware,
62
+ response_error_message="Internal server error",
63
+ response_status_code=500
64
+ )
65
+
66
+ @app.get("/")
67
+ async def root():
68
+ # This exception will be caught by the middleware
69
+ raise ValueError("Something went wrong")
70
+ ```
71
+
72
+ 2. RequestIDMiddleware
73
+
74
+ *Purpose:* Add request ID tracking to headers and logs for better request correlation.
75
+
76
+ ```python
77
+ from fastapi import FastAPI
78
+ from ash_utils.middlewares import RequestIDMiddleware
79
+
80
+ app = FastAPI()
81
+
82
+ # Add middleware with default header name (X-Request-ID)
83
+ app.add_middleware(RequestIDMiddleware)
84
+
85
+ @app.get("/")
86
+ async def root():
87
+ return {"message": "Hello World"}
88
+ ```
89
+
90
+ Example Request/Response:
91
+
92
+ ```http
93
+ GET / HTTP/1.1
94
+ Host: localhost:8000
95
+ X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
96
+
97
+ HTTP/1.1 200 OK
98
+ X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
99
+ ```
100
+
101
+ 3. BaseApi (HTTP Client)
102
+
103
+ *Purpose:* Make HTTP requests with automatic error handling and request ID propagation.
104
+
105
+ ```python
106
+ from http import HTTPMethod
107
+ from urllib.parse import urljoin
108
+
109
+ from ash_utils.apis.base_api import BaseApi
110
+ from httpx import AsyncClient
111
+ from py_cachify import cached
112
+
113
+ import constants
114
+ from domain.entities.common import PartnerConfigEntity
115
+
116
+
117
+ class ClientManagementServiceApi(BaseApi):
118
+ PARTNER_PATH = "/api/v1/partners/{partner_id}"
119
+
120
+ def __init__(self, url: str, api_key: str, client: AsyncClient):
121
+ self.token = api_key
122
+ self.base_url = url
123
+ self.headers = {"x-api-key": api_key}
124
+ super().__init__(client=client)
125
+
126
+ @cached(key=constants.PARTNER_CONFIG_CACHE_KEY, ttl=constants.PARTNER_CONFIG_CACHE_TTL)
127
+ async def get_partner_config(self, partner_id: str) -> PartnerConfigEntity:
128
+ url = urljoin(self.base_url, self.PARTNER_PATH.format(partner_id=partner_id))
129
+
130
+ response = await self._send_request(
131
+ method=HTTPMethod.GET,
132
+ url=url,
133
+ headers=self.headers,
134
+ )
135
+
136
+ response_data = response.json()
137
+
138
+ return PartnerConfigEntity(**response_data)
139
+
140
+ ```
141
+
142
+ 4. Security Headers Configuration
143
+
144
+ *Purpose:* This function provides a pre-configured security header setup for FastAPI applications following security best practices.
145
+
146
+ ```python
147
+ from fastapi import FastAPI
148
+ from ash_utils.middlewares import configure_security_headers
149
+
150
+ app = FastAPI()
151
+ configure_security_headers(app)
152
+
153
+ @app.get("/")
154
+ async def root():
155
+ return {"message": "Hello Secure World!"}
156
+ ```
157
+
158
+ The configure_security_headers function adds these security middlewares with safe defaults:
159
+ - Content Security Policy (CSP)
160
+ - X-Content-Type-Options
161
+ - Referrer-Policy
162
+ - X-Frame-Options
163
+ - HTTP Strict Transport Security (HSTS)
164
+ - Permissions-Policy
165
+
166
+
167
+ ### Configuration
168
+ Middleware Configuration Options:
169
+ - CatchUnexpectedExceptionsMiddleware
170
+ - `response_error_message`: Error message to return to clients
171
+ - `response_status_code`: HTTP status code to return (default: 500)
172
+ - RequestIDMiddleware
173
+ - `header_name`: Custom header name for request ID (default: X-Request-ID)
174
+ - BaseApi Configuration
175
+ - `request_id_header_name`: Header name for request ID propagation (default: X-Request-ID)
176
+
177
+
178
+ ### Error Handling
179
+ The BaseApi class provides two custom exceptions:
180
+
181
+ - `ThirdPartyRequestError`: For network-level errors
182
+ - `ThirdPartyHttpStatusError`: For HTTP 4xx/5xx responses
183
+
184
+
185
+ ### Best Practices
186
+ - Add CatchUnexpectedExceptionsMiddleware first in the middleware chain
187
+ - Configure a meaningful error message for production environments
188
+ - Use the BaseApi for all external API calls to ensure consistent error handling
@@ -0,0 +1,174 @@
1
+ # ash-utils
2
+
3
+ Python library containing common utilities used across various ASH projects.
4
+
5
+ ## Features
6
+
7
+ 1. **CatchUnexpectedExceptionsMiddleware** - Global exception handler for unexpected errors
8
+ 2. **RequestIDMiddleware** - Request ID tracking for improved logging and tracing
9
+ 3. **BaseApi** - Base HTTP client with built-in error handling and request ID propagation
10
+ 4. **configure_security_headers** - Function provides a pre-configured security header setup for FastAPI applications following security best practices.
11
+
12
+ ## Installation
13
+
14
+ ### PyPi
15
+
16
+ ```shell
17
+ pip install ashwelness-utils
18
+
19
+ # OR
20
+
21
+ poetry add ashwelness-utils
22
+ ```
23
+
24
+ ### From github
25
+ In order to install Ash DAL directly from GitHub repository, run:
26
+ ```shell
27
+ pip install git+https://github.com/meetash/ash-utils.git@main
28
+
29
+ # OR
30
+
31
+ poetry add git+https://github.com/meetash/ash-utils.git@main
32
+ ```
33
+
34
+ ### Usage
35
+ 1. CatchUnexpectedExceptionsMiddleware
36
+
37
+ *Purpose:* Catch all unexpected exceptions and return a standardized error response.
38
+
39
+ ```python
40
+ from fastapi import FastAPI
41
+ from ash_utils.middlewares import CatchUnexpectedExceptionsMiddleware
42
+
43
+ app = FastAPI()
44
+
45
+ # Add middleware with custom error message
46
+ app.add_middleware(
47
+ CatchUnexpectedExceptionsMiddleware,
48
+ response_error_message="Internal server error",
49
+ response_status_code=500
50
+ )
51
+
52
+ @app.get("/")
53
+ async def root():
54
+ # This exception will be caught by the middleware
55
+ raise ValueError("Something went wrong")
56
+ ```
57
+
58
+ 2. RequestIDMiddleware
59
+
60
+ *Purpose:* Add request ID tracking to headers and logs for better request correlation.
61
+
62
+ ```python
63
+ from fastapi import FastAPI
64
+ from ash_utils.middlewares import RequestIDMiddleware
65
+
66
+ app = FastAPI()
67
+
68
+ # Add middleware with default header name (X-Request-ID)
69
+ app.add_middleware(RequestIDMiddleware)
70
+
71
+ @app.get("/")
72
+ async def root():
73
+ return {"message": "Hello World"}
74
+ ```
75
+
76
+ Example Request/Response:
77
+
78
+ ```http
79
+ GET / HTTP/1.1
80
+ Host: localhost:8000
81
+ X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
82
+
83
+ HTTP/1.1 200 OK
84
+ X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
85
+ ```
86
+
87
+ 3. BaseApi (HTTP Client)
88
+
89
+ *Purpose:* Make HTTP requests with automatic error handling and request ID propagation.
90
+
91
+ ```python
92
+ from http import HTTPMethod
93
+ from urllib.parse import urljoin
94
+
95
+ from ash_utils.apis.base_api import BaseApi
96
+ from httpx import AsyncClient
97
+ from py_cachify import cached
98
+
99
+ import constants
100
+ from domain.entities.common import PartnerConfigEntity
101
+
102
+
103
+ class ClientManagementServiceApi(BaseApi):
104
+ PARTNER_PATH = "/api/v1/partners/{partner_id}"
105
+
106
+ def __init__(self, url: str, api_key: str, client: AsyncClient):
107
+ self.token = api_key
108
+ self.base_url = url
109
+ self.headers = {"x-api-key": api_key}
110
+ super().__init__(client=client)
111
+
112
+ @cached(key=constants.PARTNER_CONFIG_CACHE_KEY, ttl=constants.PARTNER_CONFIG_CACHE_TTL)
113
+ async def get_partner_config(self, partner_id: str) -> PartnerConfigEntity:
114
+ url = urljoin(self.base_url, self.PARTNER_PATH.format(partner_id=partner_id))
115
+
116
+ response = await self._send_request(
117
+ method=HTTPMethod.GET,
118
+ url=url,
119
+ headers=self.headers,
120
+ )
121
+
122
+ response_data = response.json()
123
+
124
+ return PartnerConfigEntity(**response_data)
125
+
126
+ ```
127
+
128
+ 4. Security Headers Configuration
129
+
130
+ *Purpose:* This function provides a pre-configured security header setup for FastAPI applications following security best practices.
131
+
132
+ ```python
133
+ from fastapi import FastAPI
134
+ from ash_utils.middlewares import configure_security_headers
135
+
136
+ app = FastAPI()
137
+ configure_security_headers(app)
138
+
139
+ @app.get("/")
140
+ async def root():
141
+ return {"message": "Hello Secure World!"}
142
+ ```
143
+
144
+ The configure_security_headers function adds these security middlewares with safe defaults:
145
+ - Content Security Policy (CSP)
146
+ - X-Content-Type-Options
147
+ - Referrer-Policy
148
+ - X-Frame-Options
149
+ - HTTP Strict Transport Security (HSTS)
150
+ - Permissions-Policy
151
+
152
+
153
+ ### Configuration
154
+ Middleware Configuration Options:
155
+ - CatchUnexpectedExceptionsMiddleware
156
+ - `response_error_message`: Error message to return to clients
157
+ - `response_status_code`: HTTP status code to return (default: 500)
158
+ - RequestIDMiddleware
159
+ - `header_name`: Custom header name for request ID (default: X-Request-ID)
160
+ - BaseApi Configuration
161
+ - `request_id_header_name`: Header name for request ID propagation (default: X-Request-ID)
162
+
163
+
164
+ ### Error Handling
165
+ The BaseApi class provides two custom exceptions:
166
+
167
+ - `ThirdPartyRequestError`: For network-level errors
168
+ - `ThirdPartyHttpStatusError`: For HTTP 4xx/5xx responses
169
+
170
+
171
+ ### Best Practices
172
+ - Add CatchUnexpectedExceptionsMiddleware first in the middleware chain
173
+ - Configure a meaningful error message for production environments
174
+ - Use the BaseApi for all external API calls to ensure consistent error handling
@@ -0,0 +1 @@
1
+ __VERSION__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from ash_utils.apis.base_api import BaseApi
2
+
3
+ __all__ = ["BaseApi"]
@@ -0,0 +1,65 @@
1
+ import typing as t
2
+ from http import HTTPMethod
3
+
4
+ from httpx import AsyncClient, HTTPStatusError, RequestError, Response
5
+ from loguru import logger
6
+
7
+ from ash_utils import constants
8
+ from ash_utils.middlewares import request_id_var
9
+
10
+
11
+ class BaseApi:
12
+ class ThirdPartyRequestError(Exception):
13
+ def __init__(self, message: str):
14
+ self.message = message
15
+
16
+ class ThirdPartyHttpStatusError(Exception):
17
+ def __init__(self, status_code: int, text: str, response: Response) -> None:
18
+ self.status_code = status_code
19
+ self.text = text
20
+ self.response = response
21
+
22
+ def __init__(self, client: AsyncClient, request_id_header_name: str = constants.REQUEST_ID_HEADER_NAME):
23
+ self.client = client
24
+ self.request_id_header_name = request_id_header_name
25
+
26
+ async def _send_request(
27
+ self,
28
+ method: HTTPMethod,
29
+ url: str,
30
+ body: dict[str, t.Any] | list[int] | None = None,
31
+ params: dict[str, t.Any] | None = None,
32
+ headers: dict | None = None,
33
+ ) -> Response:
34
+ with logger.contextualize(url=url, method=method, params=params):
35
+ if headers is None:
36
+ headers = {self.request_id_header_name: request_id_var.get()}
37
+ else:
38
+ headers[self.request_id_header_name] = request_id_var.get()
39
+
40
+ logger.info("Send request")
41
+
42
+ try:
43
+ response = await self.client.request(
44
+ method=method,
45
+ url=url,
46
+ json=body,
47
+ params=params,
48
+ headers=headers,
49
+ follow_redirects=True,
50
+ )
51
+ except RequestError as ex:
52
+ raise self.ThirdPartyRequestError(message=str(ex)) from ex
53
+
54
+ try:
55
+ response.raise_for_status()
56
+ except HTTPStatusError as ex:
57
+ raise self.ThirdPartyHttpStatusError(
58
+ status_code=response.status_code,
59
+ text=response.text,
60
+ response=response,
61
+ ) from ex
62
+
63
+ logger.info(f"Response received | {response.status_code=}")
64
+
65
+ return response