FastSpine 1.0.0__py3-none-any.whl
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.
- fastspine/__init__.py +48 -0
- fastspine/abstract/owner_base.py +16 -0
- fastspine/alembic/__init__.py +4 -0
- fastspine/alembic/alembic.py +95 -0
- fastspine/alembic/config.py +40 -0
- fastspine/boostrap.py +78 -0
- fastspine/cache/cache_decorater.py +264 -0
- fastspine/cache/cache_encoder.py +87 -0
- fastspine/cache/cache_exception.py +4 -0
- fastspine/cache/cache_model.py +32 -0
- fastspine/cache/cache_service.py +144 -0
- fastspine/cache/key_builder.py +134 -0
- fastspine/cache/redis_cache.py +158 -0
- fastspine/celery/base_task.py +106 -0
- fastspine/celery/engine.py +52 -0
- fastspine/cli/scoped_typer.py +47 -0
- fastspine/ctx/ctx_pool.py +73 -0
- fastspine/database/engine.py +131 -0
- fastspine/decorators/contextualize_decorator.py +54 -0
- fastspine/decorators/retry_decorator.py +66 -0
- fastspine/decorators/upsert_decorator.py +107 -0
- fastspine/dependencies/database.py +193 -0
- fastspine/dependencies/profiler.py +37 -0
- fastspine/dependencies/repository_manager.py +202 -0
- fastspine/dependencies/services.py +140 -0
- fastspine/exception/access_exception.py +13 -0
- fastspine/exception/action_not_allowed_exception.py +13 -0
- fastspine/exception/base_app_exception.py +28 -0
- fastspine/exception/exception_handler.py +9 -0
- fastspine/exception/not_found_exception.py +13 -0
- fastspine/exception/security_exception.py +13 -0
- fastspine/exception/soft_delete_exception.py +13 -0
- fastspine/lib/__init__.py +4 -0
- fastspine/lib/contextualize.py +352 -0
- fastspine/lib/profiler.py +284 -0
- fastspine/mailer/mailer_service.py +44 -0
- fastspine/middleware/request_middleware.py +67 -0
- fastspine/middleware/session_middleware.py +38 -0
- fastspine/mixins/__init__.py +4 -0
- fastspine/mixins/representable.py +12 -0
- fastspine/mixins/soft_delete.py +41 -0
- fastspine/mixins/timestamps.py +35 -0
- fastspine/models/base.py +18 -0
- fastspine/redis/client.py +23 -0
- fastspine/repositories/abstract_repository.py +267 -0
- fastspine/repositories/base_repository.py +422 -0
- fastspine/repositories/external_base_repository.py +12 -0
- fastspine/repositories/repository_manager.py +101 -0
- fastspine/schemas/pagination_model.py +26 -0
- fastspine/services/api_service.py +292 -0
- fastspine/services/base_service.py +18 -0
- fastspine/settings/__init__.py +74 -0
- fastspine/settings/app_settings.py +5 -0
- fastspine/settings/cache_settings.py +32 -0
- fastspine/settings/celery_settings.py +10 -0
- fastspine/settings/mailer_settings.py +12 -0
- fastspine/settings/profiler_settings.py +10 -0
- fastspine/types/__init__.py +3 -0
- fastspine/types/types.py +6 -0
- fastspine/util/class_util.py +110 -0
- fastspine/util/conversion.py +37 -0
- fastspine/util/dataframe_util.py +30 -0
- fastspine/util/dates.py +34 -0
- fastspine/util/debug_util.py +29 -0
- fastspine/util/emails.py +14 -0
- fastspine/util/files.py +29 -0
- fastspine/util/math.py +3 -0
- fastspine-1.0.0.dist-info/METADATA +372 -0
- fastspine-1.0.0.dist-info/RECORD +71 -0
- fastspine-1.0.0.dist-info/WHEEL +4 -0
- fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from rich import print as rich_print
|
|
2
|
+
|
|
3
|
+
from ..settings import get_core_settings
|
|
4
|
+
|
|
5
|
+
DEBUG_COLOR = "blue"
|
|
6
|
+
WARNING_COLOR = "yellow"
|
|
7
|
+
ERROR_COLOR = "red"
|
|
8
|
+
MESSAGE_COLOR = "green"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DebugUtil:
|
|
12
|
+
"""A utility class for debugging."""
|
|
13
|
+
|
|
14
|
+
@staticmethod
|
|
15
|
+
def debug(message: str) -> None:
|
|
16
|
+
"""Log a debug message."""
|
|
17
|
+
debug_mode = get_core_settings().DEBUG_MODE
|
|
18
|
+
if debug_mode:
|
|
19
|
+
rich_print(f"[bold {DEBUG_COLOR}]DEBUG:[/] [{MESSAGE_COLOR}]{message}[/]")
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def warning(message: str) -> None:
|
|
23
|
+
"""Log a warrning message."""
|
|
24
|
+
rich_print(f"[bold {WARNING_COLOR}]DEBUG:[/][{MESSAGE_COLOR}]{message}[/]")
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def error(message: str) -> None:
|
|
28
|
+
"""Log a warrning message."""
|
|
29
|
+
rich_print(f"[bold {ERROR_COLOR}]DEBUG:[/][{MESSAGE_COLOR}] {message}[/]")
|
fastspine/util/emails.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def is_valid_email(email: str) -> bool:
|
|
5
|
+
"""Validate the email address using a regular expression.
|
|
6
|
+
|
|
7
|
+
Args:
|
|
8
|
+
email (str): The email address to validate.
|
|
9
|
+
|
|
10
|
+
Returns:
|
|
11
|
+
bool: True if the email address is valid, False otherwise.
|
|
12
|
+
"""
|
|
13
|
+
email_regex = r"^(?!.*\.\.)(?!.*\.$)(?!.*\.\.$)(?!.*@-)[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
|
|
14
|
+
return re.match(email_regex, email) is not None
|
fastspine/util/files.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from io import BytesIO
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def is_excel_file(file: BytesIO) -> bool:
|
|
6
|
+
"""Check if the given file is an Excel file based on its MIME type.
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
file (BytesIO): The file to check, provided as a BytesIO object.
|
|
10
|
+
|
|
11
|
+
Returns:
|
|
12
|
+
bool: True if the file is an Excel file, False otherwise.
|
|
13
|
+
"""
|
|
14
|
+
file.seek(0)
|
|
15
|
+
file_start = file.read(8)
|
|
16
|
+
# XLS signature (Excel 97-2003)
|
|
17
|
+
xls_signature = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
|
18
|
+
|
|
19
|
+
# XLSX signature (Excel 2007 and later)
|
|
20
|
+
xlsx_signature = b"PK\x03\x04"
|
|
21
|
+
|
|
22
|
+
return file_start == xls_signature or file_start.startswith(xlsx_signature)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def sanitize_filename(filename: str, max_length: int = 255) -> str:
|
|
26
|
+
"""Sanitize filename by removing unsafe characters and limiting length."""
|
|
27
|
+
filename = filename.strip().replace(" ", "_") # Replace spaces with underscores
|
|
28
|
+
filename = re.sub(r'[\/:*?"<>|]', "", filename) # Remove unsafe characters
|
|
29
|
+
return filename[:max_length] # Limit filename lengt
|
fastspine/util/math.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: FastSpine
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: FastAPI framework with a service-repository architecture, dependency injection, Redis caching and SQLAlchemy, Celery and Alembic integration.
|
|
5
|
+
Author-email: Aleksandar Pavlovic <sleker@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: <3.13,>=3.12
|
|
9
|
+
Requires-Dist: aiomysql>=0.3.2
|
|
10
|
+
Requires-Dist: alembic<2,>=1.16.5
|
|
11
|
+
Requires-Dist: asyncpg>=0.30.0
|
|
12
|
+
Requires-Dist: celery<6,>=5.3.1
|
|
13
|
+
Requires-Dist: ecs-logging>=2.0.0
|
|
14
|
+
Requires-Dist: fastapi-mail>=1.5.0
|
|
15
|
+
Requires-Dist: fastapi<1,>=0.100.0
|
|
16
|
+
Requires-Dist: greenlet>=3.3.2
|
|
17
|
+
Requires-Dist: httpx>=0.28.1
|
|
18
|
+
Requires-Dist: openpyxl>=3.1.5
|
|
19
|
+
Requires-Dist: pandas>=2.1.3
|
|
20
|
+
Requires-Dist: polars>=0.20.13
|
|
21
|
+
Requires-Dist: psutil>=5.9.0
|
|
22
|
+
Requires-Dist: pydantic-settings>=2.3.4
|
|
23
|
+
Requires-Dist: pydantic>=2
|
|
24
|
+
Requires-Dist: python-dateutil<3,>=2.9.0
|
|
25
|
+
Requires-Dist: redis>=5.0.7
|
|
26
|
+
Requires-Dist: rich>=14.0.0
|
|
27
|
+
Requires-Dist: sqlalchemy<3,>=2.0.36
|
|
28
|
+
Requires-Dist: starlette<0.47.0,>=0.40.0
|
|
29
|
+
Requires-Dist: termcolor>=2.3.0
|
|
30
|
+
Requires-Dist: typer>=0.24.1
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# FastSpine
|
|
34
|
+
|
|
35
|
+
FastSpine is a Python framework built on top of FastAPI that provides a service-repository
|
|
36
|
+
architecture, dependency injection, caching, and supporting infrastructure (database sessions, Celery
|
|
37
|
+
tasks, Alembic migrations, Redis, mailer) for building backend applications.
|
|
38
|
+
|
|
39
|
+
## Requirements
|
|
40
|
+
|
|
41
|
+
- Python 3.12
|
|
42
|
+
- [uv](https://docs.astral.sh/uv/) for dependency management
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
make install
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
This runs `uv sync --group dev`, installing the project and its development dependencies.
|
|
51
|
+
|
|
52
|
+
## Core concepts
|
|
53
|
+
|
|
54
|
+
### Service-repository pattern
|
|
55
|
+
|
|
56
|
+
- **Repositories** (`AbstractRepository` / `BaseRepository`) encapsulate data access for a single
|
|
57
|
+
entity or external data source, bound to a `Session` or `AsyncSession`.
|
|
58
|
+
- **Repository managers** (`RepositoryManager`) group related repositories that share the same
|
|
59
|
+
database session, and expose transaction helpers (`sync_commit`, `sync_rollback`, ...).
|
|
60
|
+
- **Services** (`BaseService`) hold business logic and depend on repository managers and/or other
|
|
61
|
+
services.
|
|
62
|
+
|
|
63
|
+
### Dependency injection
|
|
64
|
+
|
|
65
|
+
FastSpine provides two parallel sets of dependency helpers for every layer:
|
|
66
|
+
|
|
67
|
+
- `*_dep` / `get_*` factories (e.g. `service_dep`, `get_repository`, `get_repository_manager`) —
|
|
68
|
+
build FastAPI `Depends()`-compatible callables for use inside request handlers.
|
|
69
|
+
- `load_*` helpers (e.g. `load_service`, `load_repository`, `load_repository_manager`) — resolve the
|
|
70
|
+
same dependency graph eagerly, for use outside of FastAPI's request lifecycle (CLI commands, Celery
|
|
71
|
+
tasks, scripts).
|
|
72
|
+
|
|
73
|
+
### Caching
|
|
74
|
+
|
|
75
|
+
Decorators in `fastspine.cache` (`cache_response`, `cache_method`, `cache_method_async`) cache
|
|
76
|
+
function results in Redis, with support for cache-key building, distributed locking to avoid
|
|
77
|
+
cache-stampede, and pluggable encoders.
|
|
78
|
+
|
|
79
|
+
### Other building blocks
|
|
80
|
+
|
|
81
|
+
- `fastspine.database` — engine/session configuration for sync and async SQLAlchemy sessions.
|
|
82
|
+
- `fastspine.celery` — base Celery task class integrated with the session/DI lifecycle.
|
|
83
|
+
- `fastspine.alembic` — helpers for running Alembic migrations.
|
|
84
|
+
- `fastspine.redis` — Redis client setup.
|
|
85
|
+
- `fastspine.mailer` — email sending via `fastapi-mail`.
|
|
86
|
+
- `fastspine.ctx` — context-local storage pool used throughout the framework for request/session
|
|
87
|
+
scoping.
|
|
88
|
+
|
|
89
|
+
## Getting started
|
|
90
|
+
|
|
91
|
+
This walks through wiring up a new application on top of FastSpine: bootstrapping the app,
|
|
92
|
+
registering databases, and defining repositories and services.
|
|
93
|
+
|
|
94
|
+
### 1. Bootstrap the app with `FastSpineApp`
|
|
95
|
+
|
|
96
|
+
Instead of instantiating `fastapi.FastAPI` directly, use `FastSpineApp`. It accepts every keyword
|
|
97
|
+
argument `FastAPI()` does, plus `settings` (your app's settings instance) and `use_asgi_middleware`
|
|
98
|
+
(set to `True` to use the ASGI-native middleware variants, required for streaming responses):
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from fastspine import FastSpineApp
|
|
102
|
+
|
|
103
|
+
from myapp.settings import AppSettings # your pydantic_settings.BaseSettings subclass
|
|
104
|
+
|
|
105
|
+
app = FastSpineApp(settings=AppSettings(), title="My App")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 2. Configure settings with a `DBConfig` per database
|
|
109
|
+
|
|
110
|
+
Group each database's connection fields in your settings class, and expose a `DBConfig` (or
|
|
111
|
+
`DBReadonlyConfig`) for each one as a property. `service` determines the driver/dialect and whether
|
|
112
|
+
the connection is async (`DBConfig.async_mode` is derived automatically from it):
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from pydantic_settings import BaseSettings
|
|
116
|
+
|
|
117
|
+
from fastspine.database.engine import DBConfig, DBServices
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class AppSettings(BaseSettings):
|
|
121
|
+
PRIMARY_DB_NAME: str = "app"
|
|
122
|
+
PRIMARY_DB_USER: str = "app_user"
|
|
123
|
+
PRIMARY_DB_PASSWORD: str = ""
|
|
124
|
+
PRIMARY_DB_HOST: str = "localhost"
|
|
125
|
+
PRIMARY_DB_PORT: int = 5432
|
|
126
|
+
|
|
127
|
+
REPORTING_DB_NAME: str = "reporting"
|
|
128
|
+
REPORTING_DB_USER: str = "reporting_user"
|
|
129
|
+
REPORTING_DB_PASSWORD: str = ""
|
|
130
|
+
REPORTING_DB_HOST: str = "reporting.internal"
|
|
131
|
+
REPORTING_DB_PORT: int = 5432
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def primary_db_config(self) -> DBConfig:
|
|
135
|
+
return DBConfig(
|
|
136
|
+
dbname=self.PRIMARY_DB_NAME,
|
|
137
|
+
user=self.PRIMARY_DB_USER,
|
|
138
|
+
password=self.PRIMARY_DB_PASSWORD,
|
|
139
|
+
host=self.PRIMARY_DB_HOST,
|
|
140
|
+
port=self.PRIMARY_DB_PORT,
|
|
141
|
+
service=DBServices.POSTGRES,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def reporting_db_config(self) -> DBConfig:
|
|
146
|
+
return DBConfig(
|
|
147
|
+
dbname=self.REPORTING_DB_NAME,
|
|
148
|
+
user=self.REPORTING_DB_USER,
|
|
149
|
+
password=self.REPORTING_DB_PASSWORD,
|
|
150
|
+
host=self.REPORTING_DB_HOST,
|
|
151
|
+
port=self.REPORTING_DB_PORT,
|
|
152
|
+
service=DBServices.ASYNC_POSTGRES,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
settings = AppSettings()
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### 3. Define a `RepositoryManager` per database and register it, via a dedicated bootstrap module
|
|
160
|
+
|
|
161
|
+
Each database/connection your app talks to gets its own `RepositoryManager` subclass, generic over
|
|
162
|
+
the session type it uses (`Session` for sync, `AsyncSession` for async). Define them together with
|
|
163
|
+
the `register_sessions(...)` call that wires each one to its `DBConfig`, in one small, dedicated
|
|
164
|
+
module (e.g. `myapp/bootstrap.py`):
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
# myapp/bootstrap.py
|
|
168
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
169
|
+
from sqlalchemy.orm import Session
|
|
170
|
+
|
|
171
|
+
from fastspine import RepositoryManager
|
|
172
|
+
from fastspine.dependencies.database import register_sessions
|
|
173
|
+
|
|
174
|
+
from myapp.settings import settings
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class PrimaryRepositoryManager(RepositoryManager[Session]):
|
|
178
|
+
"""Repository manager for the main application database."""
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class ReportingRepositoryManager(RepositoryManager[AsyncSession]):
|
|
182
|
+
"""Repository manager for an async reporting/warehouse database."""
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
register_sessions([
|
|
186
|
+
(PrimaryRepositoryManager, settings.primary_db_config),
|
|
187
|
+
(ReportingRepositoryManager, settings.reporting_db_config),
|
|
188
|
+
])
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`register_sessions` runs as an import-time side effect, so **every process that uses these
|
|
192
|
+
repository managers must import this module before anything tries to use them** — otherwise you'll
|
|
193
|
+
hit `ValueError: ... is not registered, call register_sessions() for it first.`. Don't rely on some
|
|
194
|
+
other module happening to import it transitively; import it explicitly, first, with a comment
|
|
195
|
+
explaining why:
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
# main.py (FastAPI entrypoint)
|
|
199
|
+
import myapp.bootstrap # noqa: F401 (must run before the API router is imported)
|
|
200
|
+
|
|
201
|
+
from myapp.api import api_router
|
|
202
|
+
...
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
The same discipline applies to any other process that uses these managers — e.g. a Celery worker
|
|
206
|
+
entrypoint needs the same explicit, first import, since it's a separate process with its own import
|
|
207
|
+
state.
|
|
208
|
+
|
|
209
|
+
### 4. Define repositories
|
|
210
|
+
|
|
211
|
+
Use `BaseRepository[Model]` for repositories backed by your own Alembic-tracked SQLAlchemy models
|
|
212
|
+
(subclassing FastSpine's declarative `Base`), and `ExternalBaseRepository` for repositories that
|
|
213
|
+
talk to a database you don't own/migrate (raw queries, no ORM models):
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
from fastspine import BaseRepository, ExternalBaseRepository
|
|
217
|
+
from fastspine.models.base import Base
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class Order(Base):
|
|
221
|
+
__tablename__ = "orders"
|
|
222
|
+
# ... columns ...
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class OrderRepository(BaseRepository[Order]):
|
|
226
|
+
"""Repository for `Order` rows in the primary database."""
|
|
227
|
+
# inherits sync_get_by_id, sync_filter_by, sync_create, ... from BaseRepository
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class ReportingRepository(ExternalBaseRepository):
|
|
231
|
+
"""Repository for ad-hoc queries against the reporting database."""
|
|
232
|
+
|
|
233
|
+
async def get_monthly_totals(self) -> list[dict]:
|
|
234
|
+
return await self.afetch_list("SELECT * FROM monthly_totals")
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`BaseRepository[Model]` works against *any* database your `RepositoryManager` is wired to, not just
|
|
238
|
+
the "primary" one — the model just has to be mapped as a SQLAlchemy declarative class (subclassing
|
|
239
|
+
FastSpine's `Base`). Use it for a reporting-database table too if that table happens to have a model;
|
|
240
|
+
reach for `ExternalBaseRepository` when you want to query without maintaining a mapped model at all.
|
|
241
|
+
|
|
242
|
+
### 5. Define services that depend on one or more repository managers
|
|
243
|
+
|
|
244
|
+
A `BaseService` subclass declares the repository managers (and/or other services) it needs as
|
|
245
|
+
constructor parameters, typed by the manager class. FastSpine's DI resolves and injects them. A
|
|
246
|
+
service isn't limited to one manager — depend on as many as the use case needs:
|
|
247
|
+
|
|
248
|
+
```python
|
|
249
|
+
from fastspine import BaseService
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class OrderSyncService(BaseService):
|
|
253
|
+
"""Syncs order data between the primary database and the reporting database."""
|
|
254
|
+
|
|
255
|
+
def __init__(
|
|
256
|
+
self,
|
|
257
|
+
primary: PrimaryRepositoryManager,
|
|
258
|
+
reporting: ReportingRepositoryManager,
|
|
259
|
+
):
|
|
260
|
+
self.primary = primary
|
|
261
|
+
self.reporting = reporting
|
|
262
|
+
|
|
263
|
+
def sync(self):
|
|
264
|
+
orders = self.primary.get(OrderRepository).sync_filter_by()
|
|
265
|
+
self.reporting.get(ReportingRepository).save(orders)
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### 6. Use the service
|
|
269
|
+
|
|
270
|
+
Inside a FastAPI route, inject it with `service_dep`:
|
|
271
|
+
|
|
272
|
+
```python
|
|
273
|
+
from typing import Annotated
|
|
274
|
+
|
|
275
|
+
from fastapi import Depends
|
|
276
|
+
|
|
277
|
+
from fastspine import service_dep
|
|
278
|
+
|
|
279
|
+
OrderSyncServiceDep = Annotated[OrderSyncService, Depends(service_dep(OrderSyncService))]
|
|
280
|
+
|
|
281
|
+
@app.post("/orders/sync")
|
|
282
|
+
def sync_orders(service: OrderSyncServiceDep):
|
|
283
|
+
service.sync()
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Outside of FastAPI's request lifecycle (CLI commands, Celery tasks), use `load_service` instead,
|
|
287
|
+
which resolves the same dependency graph eagerly:
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
from fastspine import load_service
|
|
291
|
+
|
|
292
|
+
def run_sync_job():
|
|
293
|
+
service = load_service(OrderSyncService)
|
|
294
|
+
service.sync()
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### 7. Non-DI lifecycles: CLI and Celery
|
|
298
|
+
|
|
299
|
+
`load_service`/`load_repository_manager` open and cache repository managers lazily, on first use, in
|
|
300
|
+
a context-local cache — there's no FastAPI request to tell you when to close them, so something has
|
|
301
|
+
to own that scope explicitly.
|
|
302
|
+
|
|
303
|
+
**CLI** — use `ScopedTyper` in place of `typer.Typer`. It wraps every async command with
|
|
304
|
+
`command_scope`, which closes whatever repository managers the command ended up using once it
|
|
305
|
+
returns (success or exception):
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
from fastspine.cli.scoped_typer import ScopedTyper
|
|
309
|
+
|
|
310
|
+
app = ScopedTyper()
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@app.command()
|
|
314
|
+
async def sync_orders():
|
|
315
|
+
service = load_service(OrderSyncService)
|
|
316
|
+
service.sync()
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
**Celery** — subclass `fastspine.celery.base_task.BaseTask`; it clears stale per-task state before
|
|
320
|
+
each task runs and closes any repository manager sessions the task opened once it finishes (success
|
|
321
|
+
or failure) — the same scope `command_scope` provides for CLI commands, adapted to Celery's signal
|
|
322
|
+
lifecycle:
|
|
323
|
+
|
|
324
|
+
```python
|
|
325
|
+
from myapp.celery_app import celery_app
|
|
326
|
+
from fastspine.celery.base_task import BaseTask
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@celery_app.task(base=BaseTask)
|
|
330
|
+
def sync_orders_task():
|
|
331
|
+
service = load_service(OrderSyncService)
|
|
332
|
+
service.sync()
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
Both paths rely on the bootstrap module from step 3 having already registered your repository
|
|
336
|
+
managers in that process — make sure your Celery worker's entrypoint imports it explicitly (same
|
|
337
|
+
`# noqa: F401` import as the FastAPI entrypoint), since a worker is a separate process with its own
|
|
338
|
+
import state.
|
|
339
|
+
|
|
340
|
+
## Further documentation
|
|
341
|
+
|
|
342
|
+
- [Full example](_docs/example.md) — one database, one model, one repository, one service, Redis
|
|
343
|
+
caching, no Celery - every piece from the docs below wired together into one small running app.
|
|
344
|
+
- [Database](_docs/database.md) — settings → `RepositoryManager` classes → registration →
|
|
345
|
+
repositories/services, including why manager classes belong in one file and registration in
|
|
346
|
+
another (and that "bootstrap" is just a name, not a requirement).
|
|
347
|
+
- [Configuration](_docs/configuration.md) — every `CoreSettings` field (app, cache, Celery,
|
|
348
|
+
profiler, mailer) and `DBConfig`, with defaults and what each one actually controls.
|
|
349
|
+
- [Caching](_docs/caching.md) — the decorators, `CacheService`/`CachableModel`, encoders, and the
|
|
350
|
+
low-level `redis_cache` functions underneath all of them.
|
|
351
|
+
- [CLI](_docs/cli.md) — `ScopedTyper`/`command_scope`, and why CLI commands need their own
|
|
352
|
+
repository-manager lifecycle (there's no `Depends()` to open/close sessions for you).
|
|
353
|
+
- [Celery](_docs/celery.md) — `BaseTask` (dedup, session cleanup, failure fallback), and how to
|
|
354
|
+
run the worker in dev vs. prod.
|
|
355
|
+
|
|
356
|
+
## Development
|
|
357
|
+
|
|
358
|
+
Common tasks are available via `make`:
|
|
359
|
+
|
|
360
|
+
```bash
|
|
361
|
+
make install # Install project + dev dependencies
|
|
362
|
+
make test # Run the test suite with pytest
|
|
363
|
+
make ruff # Run the ruff linter
|
|
364
|
+
make ruff-formatter # Run the ruff formatter
|
|
365
|
+
make deptry # Check for unused/missing dependencies
|
|
366
|
+
make mypy # Run the mypy type checker
|
|
367
|
+
make check # Run test, ruff-formatter, ruff, deptry and mypy
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
## License
|
|
371
|
+
|
|
372
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
fastspine/__init__.py,sha256=khnlqhnknt-iWzrMjrjk9ILXl8QgG4v5oTpe2SQJ110,1614
|
|
2
|
+
fastspine/boostrap.py,sha256=BPKQsaD9gERwPyVoOeoV52QHWpe8BvsQVUCU5MB5Vac,3454
|
|
3
|
+
fastspine/abstract/owner_base.py,sha256=BfAeL3DQ5LVuKUNgriPB0Bqs85S9qvXxNSHbvuZvCUQ,420
|
|
4
|
+
fastspine/alembic/__init__.py,sha256=u6X2W0BybAP9z4Ji9t3VD60Q2V1APG6Bx4BZlyeRyTM,218
|
|
5
|
+
fastspine/alembic/alembic.py,sha256=-n9Wj4EQZm_3jXzIfOOms6Nz4J_Rmzy56-jqPi3Txqo,3691
|
|
6
|
+
fastspine/alembic/config.py,sha256=VAlkT-DHi02E_-wUmW89v64Lmm4brAFACZevyKJMYSI,1105
|
|
7
|
+
fastspine/cache/cache_decorater.py,sha256=BmpwOcfsr6lilIdVT6WmaNqE7Sn5yaWca33adT6oRAM,10149
|
|
8
|
+
fastspine/cache/cache_encoder.py,sha256=z4U3pY2jznxqnxLHM82BxPoZBGFdTyS5gOtiWvwHjZs,2495
|
|
9
|
+
fastspine/cache/cache_exception.py,sha256=xpoYXJWL88_9fTbr7hKI2uwPP0cmS8KQAky8FWzqRKc,92
|
|
10
|
+
fastspine/cache/cache_model.py,sha256=X8wpSb1NyKhCpIIISa21jEneSuaLDeXMoWS3WAcRKdI,1107
|
|
11
|
+
fastspine/cache/cache_service.py,sha256=DUzRNjSM_s4rmYNlCPxiymuVVTcGv8oAdMHCUumPNZI,5420
|
|
12
|
+
fastspine/cache/key_builder.py,sha256=aY8QoWIkF7yCCZJvnaciBKOxBTDUXoBpHAadUE_xTIQ,6046
|
|
13
|
+
fastspine/cache/redis_cache.py,sha256=ORLK7ysFWVEXQLSwj8QY5m9_r1ELfqbXW0cORRzoWSU,5174
|
|
14
|
+
fastspine/celery/base_task.py,sha256=zMUSEZdGZtFlWxHCUz-Q541e5Xu5reWgHD-1GSzotJ8,4595
|
|
15
|
+
fastspine/celery/engine.py,sha256=ECnzflWfXVH0Efp7WlmL0FLvftW9RzA0sU_KuS7Cfss,1730
|
|
16
|
+
fastspine/cli/scoped_typer.py,sha256=jSR4w0PbMxM1iaoT13ZhP1mnA22vDNzTzKn8a7Pn6XY,1735
|
|
17
|
+
fastspine/ctx/ctx_pool.py,sha256=ZWufJZ2vSwJ-UzBmDeLZCoVcdSu1Rb0hgPoLvZPQ02M,2533
|
|
18
|
+
fastspine/database/engine.py,sha256=GN4mWcZSpoNXtpEtDGGBZZ7O7lco71xLIFTu6lIG9m4,4964
|
|
19
|
+
fastspine/decorators/contextualize_decorator.py,sha256=D4VXHipeZ-9VdeomwJ0Sa7bGF3F3mgjTeyg51bltdTE,2079
|
|
20
|
+
fastspine/decorators/retry_decorator.py,sha256=d-Obj5_0siT-W88CVxm7xP05CbE-QAMlUXSdWdcQRGo,2408
|
|
21
|
+
fastspine/decorators/upsert_decorator.py,sha256=4bGoJ80WLU7A0y5rlxm7d3NZ59rtS0isdz2xl7qoDkw,4130
|
|
22
|
+
fastspine/dependencies/database.py,sha256=BWaKr4Ga8-9Fcawhy9gtbnVzsxhu-eHBoTV30_5fruM,7241
|
|
23
|
+
fastspine/dependencies/profiler.py,sha256=g7RLV89dxz0aU4s4FTO7HfD_gjKNlbnltyddm7prj58,1242
|
|
24
|
+
fastspine/dependencies/repository_manager.py,sha256=QVPetob3GQNqaCc_F8w5qlasHSv_CMM3mdrQL2vylbY,7943
|
|
25
|
+
fastspine/dependencies/services.py,sha256=IVwPL4GxBsFB65Lq43iW7wFUKhlIXzIHDqhB5TYE-tY,6623
|
|
26
|
+
fastspine/exception/access_exception.py,sha256=ZwzHtQJVo7tHGYmbiUb4o-D_ogb6Xc_y-uw_sJt9ygE,376
|
|
27
|
+
fastspine/exception/action_not_allowed_exception.py,sha256=CkPXQ92eFHW36CbDYK_NjnRjxaY4crmTgaqny-NNL3c,348
|
|
28
|
+
fastspine/exception/base_app_exception.py,sha256=OUvEWthGxl70VogSY-pBpCZstOnAJAX9PUw-hPxZ6Mk,1129
|
|
29
|
+
fastspine/exception/exception_handler.py,sha256=fJN0uc1HcVKIxi5bvObjoStv9B86pqX4-0p9ifLjICY,328
|
|
30
|
+
fastspine/exception/not_found_exception.py,sha256=5ezQmnE2x9dHezeUGcY-lLVUWL2CdEsfR6RCOYM9GY4,341
|
|
31
|
+
fastspine/exception/security_exception.py,sha256=GweAw_t8Y8PvEhyLpaq0_3Xu7RSBQtJHXpFGJ3fJYYk,370
|
|
32
|
+
fastspine/exception/soft_delete_exception.py,sha256=oG8xdOlMlH6KEotWoPMoqG2oj8qP8kZPxIu9LKZ-Dys,342
|
|
33
|
+
fastspine/lib/__init__.py,sha256=cuY4GS0gPUvpqxvz72Dry23D8SYdcqoSoujS_f6wdd4,109
|
|
34
|
+
fastspine/lib/contextualize.py,sha256=A8JaWVjplh1BliftXv-pMAqeNG9bIpMnMN5rX2zbh2Q,11484
|
|
35
|
+
fastspine/lib/profiler.py,sha256=nFKvzmMpeF5Vt21FlPVkW3-M9M5ji-2uSY7ZAhjzlJQ,10736
|
|
36
|
+
fastspine/mailer/mailer_service.py,sha256=l23Ut9pUJKX65pv0AZDiFBE72QtTkZqqkdE0nFHxVKw,1908
|
|
37
|
+
fastspine/middleware/request_middleware.py,sha256=ivaeufymauR2xLkfOL20jTt9pkllPNC8ycUn_CXcYBQ,2416
|
|
38
|
+
fastspine/middleware/session_middleware.py,sha256=BKBn-1gNrd_z_bZvI4Qs0ansqE2zox4bvpMwi2_CbS8,1270
|
|
39
|
+
fastspine/mixins/__init__.py,sha256=boUHdqxkrcBye4xKNzs9sTkXapYVdE-hVZw1zAiDgXU,197
|
|
40
|
+
fastspine/mixins/representable.py,sha256=kedLuow4hTz5zM9qWEDX7AvAY88AsOQJS_K_Hq4DpjU,449
|
|
41
|
+
fastspine/mixins/soft_delete.py,sha256=t1VwcjgSoxVus2KNyxJKVnQKm6SZyiv0I4WBMA3Udwo,1357
|
|
42
|
+
fastspine/mixins/timestamps.py,sha256=yCmh-N-9ZZRibIgP1GHdjf58mvf0dwLZqUoyWFbfVZg,1021
|
|
43
|
+
fastspine/models/base.py,sha256=TsHLB1yY_Li9wzq0XfASb8S7WvUO8snWQcONcNMSLZg,491
|
|
44
|
+
fastspine/redis/client.py,sha256=NGucpJC_NF_7KHcthgZs-6Bu4JlyEWTJZSnVDC7s7MI,608
|
|
45
|
+
fastspine/repositories/abstract_repository.py,sha256=aqee8tz4XjkVdXhLzdHbRXeITeMYRJPKcrZwaMhD_hU,10418
|
|
46
|
+
fastspine/repositories/base_repository.py,sha256=bve38TenP4GkBIyVnMrQY15UobyxnlkgNbnL7QXyryU,16335
|
|
47
|
+
fastspine/repositories/external_base_repository.py,sha256=qTUrvuqfc0eYF1TYpPKfyK_2nkAOB9TO3xSoKP96620,328
|
|
48
|
+
fastspine/repositories/repository_manager.py,sha256=pW4gEY4XItZcMdFYohpgCr5J7C7vpfOnRoeTJ7eYjGA,4170
|
|
49
|
+
fastspine/schemas/pagination_model.py,sha256=d9BgD742dYdndH5jcZPPDGC4UUO4i94302_QnGcGjCA,619
|
|
50
|
+
fastspine/services/api_service.py,sha256=wwKzncr0_GBmCnarD_aLVsfvnwbRCkWUCi6RtThBC6A,9350
|
|
51
|
+
fastspine/services/base_service.py,sha256=QUPQNjDZFqbePhvgbH6tMuV6gnK-N6RnHdv6sHeT1Gw,421
|
|
52
|
+
fastspine/settings/__init__.py,sha256=PgB2oCsfIP9QR0iHBNmp48qKK9rIAzQYNmnDZYahVs4,2642
|
|
53
|
+
fastspine/settings/app_settings.py,sha256=MvIToN-JF7AyAx9BFklIl9LRClY9xS4ZO3f2p8g0x54,181
|
|
54
|
+
fastspine/settings/cache_settings.py,sha256=U6Ruff1yUHCY4IVRl1tM5neQy2Z0ypCPsjEDT6ZwBdM,1242
|
|
55
|
+
fastspine/settings/celery_settings.py,sha256=TEFVquHBRnvWMiP-_JzyLmJ9d_qmNmSCyJKDTnt1JCA,450
|
|
56
|
+
fastspine/settings/mailer_settings.py,sha256=wnx3Z_xQR-UckLn63XceK06nTvHV2OxbCSZMmPjQNFg,403
|
|
57
|
+
fastspine/settings/profiler_settings.py,sha256=-TQJeLGI8ja5GbhR5ZN4DJRMokJD-NWeqhz1L0WtDR0,262
|
|
58
|
+
fastspine/types/__init__.py,sha256=KLR7J8_vOkVNlLkzRIUnFmkgMiiUKSqhlyMNGFmXgjI,80
|
|
59
|
+
fastspine/types/types.py,sha256=wSocW12WooMXNP94oZhUwQwvgXz2OlMCX4gNTUOTMG4,203
|
|
60
|
+
fastspine/util/class_util.py,sha256=JkUDzanf5abxzFAylRQ4dJxcfEDAOc8GKtsfJQsDBtc,3683
|
|
61
|
+
fastspine/util/conversion.py,sha256=3frO5R6uCFob_kWG0pIVX8ZjJYFp361MQ5KwMPi9deQ,913
|
|
62
|
+
fastspine/util/dataframe_util.py,sha256=iBv8-Pf0xTUUIyk-EuTnRUq1mJ39BxOComyE-MzKoRg,1047
|
|
63
|
+
fastspine/util/dates.py,sha256=ZlalzYLHX3lMqdqxfQU3qbO4Y-xnQeI6MmtWkCIYBeY,1161
|
|
64
|
+
fastspine/util/debug_util.py,sha256=LvXtAxEoUOr4wNA6YfZIhaQtpSE12wJai0aXT0M4yTY,840
|
|
65
|
+
fastspine/util/emails.py,sha256=KvVYn_MSAel_vPF7oZVxEP1YXKyCpCTDb0SD_ouODhw,426
|
|
66
|
+
fastspine/util/files.py,sha256=YuwcqFYF7X3zuF5nwxBZE8uCLaaoypBIr8WOtToqFe4,992
|
|
67
|
+
fastspine/util/math.py,sha256=qDrnKdDhSOs7CdhwSJgQ2NNdtc3iK5xRE8jcQ8Wo38g,164
|
|
68
|
+
fastspine-1.0.0.dist-info/METADATA,sha256=wDQh0kIqjAi1fndcwLG2ATEgWW2ANaZqH4BSnvJpuTs,13588
|
|
69
|
+
fastspine-1.0.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
70
|
+
fastspine-1.0.0.dist-info/licenses/LICENSE,sha256=wOAzjmu0fUGiSBtl3-BTwNnJp2g0_G9FNvA7YpubjMc,1076
|
|
71
|
+
fastspine-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aleksandar Pavlovic
|
|
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.
|