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,292 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
from pydantic import BaseModel, ValidationError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class APIAuthConfig(BaseModel):
|
|
11
|
+
"""Base config for API authentication."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class APIKeyConfig(APIAuthConfig):
|
|
17
|
+
"""API Key authentication."""
|
|
18
|
+
|
|
19
|
+
api_key: str
|
|
20
|
+
key_header: str = "X-API-KEY"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class APIKeySecretConfig(APIAuthConfig):
|
|
24
|
+
"""API Key + Secret authentication."""
|
|
25
|
+
|
|
26
|
+
api_key_id: str
|
|
27
|
+
api_key_secret: str
|
|
28
|
+
key_id_header: str = "X-API-KEY-ID"
|
|
29
|
+
key_secret_header: str = ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class BearerTokenConfig(APIAuthConfig):
|
|
33
|
+
"""Bearer token authentication."""
|
|
34
|
+
|
|
35
|
+
token: str
|
|
36
|
+
header: str = "Authorization"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class BasicAuthConfig(APIAuthConfig):
|
|
40
|
+
"""Basic authentication."""
|
|
41
|
+
|
|
42
|
+
username: str
|
|
43
|
+
password: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CustomAuthConfig(APIAuthConfig):
|
|
47
|
+
"""Custom headers authentication."""
|
|
48
|
+
|
|
49
|
+
headers: dict[str, str]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class APIError(Exception):
|
|
53
|
+
"""Base API error."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, message: str, status_code: int | None = None, response_data: dict | None = None):
|
|
56
|
+
self.message = message
|
|
57
|
+
self.status_code = status_code
|
|
58
|
+
self.response_data = response_data
|
|
59
|
+
super().__init__(message)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class APIValidationError(APIError):
|
|
63
|
+
"""API response validation error."""
|
|
64
|
+
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class AbstractAPIService(ABC):
|
|
69
|
+
"""Abstract base class for external API services.
|
|
70
|
+
|
|
71
|
+
Provides common functionality for:
|
|
72
|
+
- HTTP client management
|
|
73
|
+
- Authentication handling
|
|
74
|
+
- Response parsing to Pydantic models
|
|
75
|
+
- Error handling and retries
|
|
76
|
+
- Logging
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
base_url: str,
|
|
82
|
+
auth_config: APIAuthConfig,
|
|
83
|
+
timeout: int = 30,
|
|
84
|
+
max_retries: int = 3,
|
|
85
|
+
retry_delay: float = 1.0,
|
|
86
|
+
client: httpx.AsyncClient | None = None,
|
|
87
|
+
):
|
|
88
|
+
self.base_url = base_url.rstrip("/")
|
|
89
|
+
self.auth_config = auth_config
|
|
90
|
+
self.timeout = timeout
|
|
91
|
+
self.max_retries = max_retries
|
|
92
|
+
self.retry_delay = retry_delay
|
|
93
|
+
self._client = client
|
|
94
|
+
self.logger = logging.getLogger(self.__class__.__name__)
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def client(self) -> httpx.AsyncClient:
|
|
98
|
+
"""Lazy initialization of HTTP client."""
|
|
99
|
+
if self._client is None:
|
|
100
|
+
headers = self._build_auth_headers()
|
|
101
|
+
headers.update(self._get_default_headers())
|
|
102
|
+
|
|
103
|
+
self._client = httpx.AsyncClient(timeout=self.timeout, headers=headers)
|
|
104
|
+
return self._client
|
|
105
|
+
|
|
106
|
+
def _build_auth_headers(self) -> dict[str, str]:
|
|
107
|
+
"""Build authentication headers based on auth config."""
|
|
108
|
+
headers = {}
|
|
109
|
+
|
|
110
|
+
if isinstance(self.auth_config, APIKeyConfig):
|
|
111
|
+
headers[self.auth_config.key_header] = self.auth_config.api_key
|
|
112
|
+
|
|
113
|
+
elif isinstance(self.auth_config, APIKeySecretConfig):
|
|
114
|
+
headers[self.auth_config.key_id_header] = self.auth_config.api_key_id
|
|
115
|
+
headers[self.auth_config.key_secret_header] = self.auth_config.api_key_secret
|
|
116
|
+
|
|
117
|
+
elif isinstance(self.auth_config, BearerTokenConfig):
|
|
118
|
+
headers[self.auth_config.header] = f"Bearer {self.auth_config.token}"
|
|
119
|
+
|
|
120
|
+
elif isinstance(self.auth_config, BasicAuthConfig):
|
|
121
|
+
import base64
|
|
122
|
+
|
|
123
|
+
credentials = base64.b64encode(f"{self.auth_config.username}:{self.auth_config.password}".encode()).decode()
|
|
124
|
+
headers["Authorization"] = f"Basic {credentials}"
|
|
125
|
+
|
|
126
|
+
elif isinstance(self.auth_config, CustomAuthConfig):
|
|
127
|
+
headers.update(self.auth_config.headers)
|
|
128
|
+
|
|
129
|
+
return headers
|
|
130
|
+
|
|
131
|
+
@abstractmethod
|
|
132
|
+
def _get_default_headers(self) -> dict[str, str]:
|
|
133
|
+
"""Override to provide service-specific default headers."""
|
|
134
|
+
return {"Content-Type": "application/json", "Accept": "application/json"}
|
|
135
|
+
|
|
136
|
+
def _build_url(self, endpoint: str) -> str:
|
|
137
|
+
"""Build full URL for endpoint."""
|
|
138
|
+
return f"{self.base_url}/{endpoint.lstrip('/')}"
|
|
139
|
+
|
|
140
|
+
async def _make_request(
|
|
141
|
+
self,
|
|
142
|
+
method: str,
|
|
143
|
+
endpoint: str,
|
|
144
|
+
data: dict[str, Any] | None = None,
|
|
145
|
+
params: dict[str, Any] | None = None,
|
|
146
|
+
headers: dict[str, str] | None = None,
|
|
147
|
+
) -> httpx.Response:
|
|
148
|
+
"""Make HTTP request with retry logic."""
|
|
149
|
+
url = self._build_url(endpoint)
|
|
150
|
+
request_headers = headers or {}
|
|
151
|
+
|
|
152
|
+
for attempt in range(self.max_retries):
|
|
153
|
+
try:
|
|
154
|
+
response = await self.client.request(
|
|
155
|
+
method=method, url=url, json=data, params=params, headers=request_headers
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
if response.status_code < 500: # Don't retry client errors
|
|
159
|
+
return response
|
|
160
|
+
|
|
161
|
+
# Server error - retry
|
|
162
|
+
if attempt < self.max_retries - 1:
|
|
163
|
+
await asyncio.sleep(self.retry_delay * (2**attempt))
|
|
164
|
+
continue
|
|
165
|
+
|
|
166
|
+
return response
|
|
167
|
+
|
|
168
|
+
except httpx.TimeoutException as e:
|
|
169
|
+
if attempt < self.max_retries - 1:
|
|
170
|
+
await asyncio.sleep(self.retry_delay * (2**attempt))
|
|
171
|
+
continue
|
|
172
|
+
raise APIError(f"Request timeout after {self.max_retries} attempts", response_data=None) from e
|
|
173
|
+
|
|
174
|
+
except httpx.RequestError as e:
|
|
175
|
+
if attempt < self.max_retries - 1:
|
|
176
|
+
await asyncio.sleep(self.retry_delay * (2**attempt))
|
|
177
|
+
continue
|
|
178
|
+
raise APIError(f"Request failed: {str(e)}", response_data=None) from e
|
|
179
|
+
|
|
180
|
+
return httpx.Response(status_code=500) # Fallback, should not reach here
|
|
181
|
+
|
|
182
|
+
def _parse_response[T: BaseModel](self, response: httpx.Response, model_class: type[T]) -> T:
|
|
183
|
+
"""Parse HTTP response to Pydantic model."""
|
|
184
|
+
try:
|
|
185
|
+
# Check for HTTP errors
|
|
186
|
+
if not response.is_success:
|
|
187
|
+
error_data = None
|
|
188
|
+
try:
|
|
189
|
+
error_data = response.json()
|
|
190
|
+
except Exception:
|
|
191
|
+
error_data = {"detail": response.text}
|
|
192
|
+
|
|
193
|
+
raise APIError(
|
|
194
|
+
f"API request failed: {response.status_code}",
|
|
195
|
+
status_code=response.status_code,
|
|
196
|
+
response_data=error_data,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
# Parse response data
|
|
200
|
+
response_data = response.json()
|
|
201
|
+
return model_class(**response_data)
|
|
202
|
+
|
|
203
|
+
except ValidationError as e:
|
|
204
|
+
raise APIValidationError(
|
|
205
|
+
f"Invalid response format: {str(e)}",
|
|
206
|
+
status_code=response.status_code,
|
|
207
|
+
response_data=response_data if "response_data" in locals() else None,
|
|
208
|
+
) from e
|
|
209
|
+
except Exception as e:
|
|
210
|
+
raise APIError(f"Response parsing failed: {str(e)}") from e
|
|
211
|
+
|
|
212
|
+
async def _get[T: BaseModel](
|
|
213
|
+
self, endpoint: str, params: dict | None = None, response_model: type[T] | None = None
|
|
214
|
+
) -> dict | T:
|
|
215
|
+
"""Make GET request."""
|
|
216
|
+
response = await self._make_request("GET", endpoint, params=params)
|
|
217
|
+
|
|
218
|
+
if response_model:
|
|
219
|
+
return self._parse_response(response, response_model)
|
|
220
|
+
|
|
221
|
+
response.raise_for_status()
|
|
222
|
+
return response.json()
|
|
223
|
+
|
|
224
|
+
async def _post[T: BaseModel](
|
|
225
|
+
self, endpoint: str, data: dict | None = None, response_model: type[T] | None = None
|
|
226
|
+
) -> dict | T:
|
|
227
|
+
"""Make POST request."""
|
|
228
|
+
response = await self._make_request("POST", endpoint, data=data)
|
|
229
|
+
|
|
230
|
+
if response_model:
|
|
231
|
+
return self._parse_response(response, response_model)
|
|
232
|
+
|
|
233
|
+
response.raise_for_status()
|
|
234
|
+
return response.json()
|
|
235
|
+
|
|
236
|
+
async def _post_model[T: BaseModel](
|
|
237
|
+
self,
|
|
238
|
+
endpoint: str,
|
|
239
|
+
response_model: type[T],
|
|
240
|
+
data: dict[str, Any] | None = None,
|
|
241
|
+
) -> T:
|
|
242
|
+
"""Make POST request."""
|
|
243
|
+
response = await self._make_request("POST", endpoint, data=data)
|
|
244
|
+
|
|
245
|
+
return self._parse_response(response, response_model)
|
|
246
|
+
|
|
247
|
+
async def _put[T: BaseModel](
|
|
248
|
+
self, endpoint: str, data: dict | None = None, response_model: type[T] | None = None
|
|
249
|
+
) -> dict | T:
|
|
250
|
+
"""Make PUT request."""
|
|
251
|
+
response = await self._make_request("PUT", endpoint, data=data)
|
|
252
|
+
|
|
253
|
+
if response_model:
|
|
254
|
+
return self._parse_response(response, response_model)
|
|
255
|
+
|
|
256
|
+
response.raise_for_status()
|
|
257
|
+
return response.json()
|
|
258
|
+
|
|
259
|
+
async def _delete[T: BaseModel](self, endpoint: str, response_model: type[T] | None = None) -> dict | T | None:
|
|
260
|
+
"""Make DELETE request."""
|
|
261
|
+
response = await self._make_request("DELETE", endpoint)
|
|
262
|
+
|
|
263
|
+
if response.status_code == 204: # No content
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
if response_model:
|
|
267
|
+
return self._parse_response(response, response_model)
|
|
268
|
+
|
|
269
|
+
response.raise_for_status()
|
|
270
|
+
return response.json()
|
|
271
|
+
|
|
272
|
+
@classmethod
|
|
273
|
+
def dependency(cls, *args, **kwargs):
|
|
274
|
+
"""Create a FastAPI dependency that returns a default instance of this service."""
|
|
275
|
+
|
|
276
|
+
def factory() -> "AbstractAPIService":
|
|
277
|
+
return cls(*args, **kwargs)
|
|
278
|
+
|
|
279
|
+
return factory
|
|
280
|
+
|
|
281
|
+
async def close(self):
|
|
282
|
+
"""Close HTTP client."""
|
|
283
|
+
if self._client:
|
|
284
|
+
await self._client.aclose()
|
|
285
|
+
|
|
286
|
+
async def __aenter__(self):
|
|
287
|
+
"""Context manager entry."""
|
|
288
|
+
return self
|
|
289
|
+
|
|
290
|
+
async def __aexit__(self, *args):
|
|
291
|
+
"""Context manager exit."""
|
|
292
|
+
await self.close()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from abc import ABC
|
|
2
|
+
|
|
3
|
+
from ..dependencies.profiler import fetch_profiler
|
|
4
|
+
from ..lib.profiler import Profiler
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BaseService(ABC): # noqa: B024
|
|
8
|
+
"""Base service class."""
|
|
9
|
+
|
|
10
|
+
_profiler: Profiler | None = None
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def profiler(self) -> Profiler:
|
|
14
|
+
"""Get the Profiler instance."""
|
|
15
|
+
if self._profiler is None:
|
|
16
|
+
self._profiler = fetch_profiler()
|
|
17
|
+
|
|
18
|
+
return self._profiler
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import types
|
|
2
|
+
from functools import lru_cache
|
|
3
|
+
from typing import Union, get_args, get_origin
|
|
4
|
+
|
|
5
|
+
from pydantic_settings import BaseSettings
|
|
6
|
+
|
|
7
|
+
from ..ctx.ctx_pool import ctxpool
|
|
8
|
+
from ..mixins.representable import RepresentableMixin
|
|
9
|
+
from .app_settings import AppSettings
|
|
10
|
+
from .cache_settings import CacheSettings
|
|
11
|
+
from .celery_settings import CelerySettings
|
|
12
|
+
from .mailer_settings import MailerSettings
|
|
13
|
+
from .profiler_settings import ProfilerSettings
|
|
14
|
+
|
|
15
|
+
__all__ = ["CoreSettings", "init_core_settings", "get_core_settings"]
|
|
16
|
+
|
|
17
|
+
CORE_SETTINGS_CTX_NAME = "core_settings_ctx"
|
|
18
|
+
core_settings_ctx = ctxpool.new(CORE_SETTINGS_CTX_NAME, persistant=True)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CoreSettings(AppSettings, CacheSettings, CelerySettings, MailerSettings, ProfilerSettings, RepresentableMixin):
|
|
22
|
+
"""Settings class for core application settings and secrets management."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, settings: BaseSettings | None = None):
|
|
25
|
+
"""Initialize the CoreSettings with optional BaseSettings."""
|
|
26
|
+
if settings:
|
|
27
|
+
self._set_properties(settings)
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def is_optional_type(annotation) -> bool:
|
|
31
|
+
"""Check if the annotation is an optional type."""
|
|
32
|
+
# Handle new Union syntax (T | None) from Python 3.10+
|
|
33
|
+
if isinstance(annotation, types.UnionType):
|
|
34
|
+
return type(None) in annotation.__args__
|
|
35
|
+
|
|
36
|
+
# Handle old Union syntax (Union[T, None])
|
|
37
|
+
return get_origin(annotation) is Union and type(None) in get_args(annotation)
|
|
38
|
+
|
|
39
|
+
def _set_properties(self, settings: BaseSettings):
|
|
40
|
+
from typing import get_type_hints
|
|
41
|
+
|
|
42
|
+
type_hints = get_type_hints(self.__class__)
|
|
43
|
+
|
|
44
|
+
for key, annotation in type_hints.items():
|
|
45
|
+
is_optional = self.is_optional_type(annotation)
|
|
46
|
+
if not hasattr(settings, key):
|
|
47
|
+
if not is_optional:
|
|
48
|
+
raise RuntimeError(f"Missing required setting: {key}")
|
|
49
|
+
continue
|
|
50
|
+
|
|
51
|
+
value = getattr(settings, key, None)
|
|
52
|
+
|
|
53
|
+
if value is None and not is_optional:
|
|
54
|
+
raise RuntimeError(f"Setting '{key}' cannot be None (not Optional)")
|
|
55
|
+
|
|
56
|
+
setattr(self, key, value)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def init_core_settings(settings: BaseSettings | None = None) -> CoreSettings:
|
|
60
|
+
"""Initialize the core settings."""
|
|
61
|
+
core_settings = CoreSettings(settings=settings)
|
|
62
|
+
|
|
63
|
+
ctxpool.set(CORE_SETTINGS_CTX_NAME, core_settings)
|
|
64
|
+
return core_settings
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@lru_cache
|
|
68
|
+
def get_core_settings() -> CoreSettings:
|
|
69
|
+
"""Get the core settings."""
|
|
70
|
+
_core_settings = ctxpool.get(CORE_SETTINGS_CTX_NAME)
|
|
71
|
+
|
|
72
|
+
if _core_settings is None:
|
|
73
|
+
raise RuntimeError("CoreSettings is not initialized")
|
|
74
|
+
return _core_settings
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import contextvars
|
|
2
|
+
|
|
3
|
+
_cache_enabled_var: contextvars.ContextVar[bool | None] = contextvars.ContextVar("_cache_enabled_var", default=None)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CacheSettings:
|
|
7
|
+
"""Settings class for cache configuration."""
|
|
8
|
+
|
|
9
|
+
REDIS_USER: str = ""
|
|
10
|
+
REDIS_PASSWORD: str = ""
|
|
11
|
+
REDIS_PORT: int = 6379
|
|
12
|
+
REDIS_HOST: str = "localhost"
|
|
13
|
+
CACHE_ENABLED: bool = True
|
|
14
|
+
CACHE_KEY_PREFIX: str | None = None
|
|
15
|
+
CACHED_DISABLED_USERS: list[str] = []
|
|
16
|
+
|
|
17
|
+
def get_redis_url(self):
|
|
18
|
+
"""Construct the Redis URL from the settings."""
|
|
19
|
+
return f"redis://{self.REDIS_USER}:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}"
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def is_cache_enabled(self) -> bool:
|
|
23
|
+
"""Check if caching is enabled for the current request context.
|
|
24
|
+
|
|
25
|
+
Falls back to the global CACHE_ENABLED setting when no request has set a context-specific value.
|
|
26
|
+
"""
|
|
27
|
+
value = _cache_enabled_var.get()
|
|
28
|
+
return value if value is not None else self.CACHE_ENABLED
|
|
29
|
+
|
|
30
|
+
def set_cache_enabled(self, user_email: str):
|
|
31
|
+
"""Set cache state for the current request context based on global setting and user-specific rules."""
|
|
32
|
+
_cache_enabled_var.set(self.CACHE_ENABLED and user_email not in self.CACHED_DISABLED_USERS)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
class CelerySettings:
|
|
2
|
+
"""Settings class for Celery configuration."""
|
|
3
|
+
|
|
4
|
+
CELERY_RESULT_EXPIRES: int = 7 * 24 * 60 * 60 # 7 days
|
|
5
|
+
CELERY_BROKER_URI: str = ""
|
|
6
|
+
CELERY_BACKEND_URI: str = "redis://localhost:6385/0"
|
|
7
|
+
CELERY_MAIN_NAME: str = "_redis_main"
|
|
8
|
+
CELERY_TASK_FOLDERS: list[str] = []
|
|
9
|
+
WORKERS_ON: bool = True # Whether workers are enabled
|
|
10
|
+
VISIBILITY_TIMEOUT: int = 3600 # Default visibility timeout for tasks in seconds
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
class MailerSettings:
|
|
2
|
+
"""Settings class for mailer configuration."""
|
|
3
|
+
|
|
4
|
+
MAIL_USERNAME: str | None = None
|
|
5
|
+
MAIL_PASSWORD: str | None = None
|
|
6
|
+
MAIL_FROM: str | None = None
|
|
7
|
+
MAIL_PORT: int | None = None
|
|
8
|
+
MAIL_SERVER: str | None = None
|
|
9
|
+
MAIL_STARTTLS: bool | None = None
|
|
10
|
+
MAIL_SSL_TLS: bool | None = None
|
|
11
|
+
USE_CREDENTIALS: bool | None = None
|
|
12
|
+
VALIDATE_CERTS: bool | None = None
|
fastspine/types/types.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Any, get_type_hints
|
|
4
|
+
|
|
5
|
+
import polars as pl
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
# worker scope cache, prewarm up cache
|
|
9
|
+
annotations_classes: dict[type[Any], dict[str, Any]] = {}
|
|
10
|
+
|
|
11
|
+
annotations_cache: dict[type[Any], dict[str, Any]] = {}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_class_annotations[T](service_class: type[T]):
|
|
15
|
+
"""Get the annotations of a class."""
|
|
16
|
+
if service_class in annotations_cache:
|
|
17
|
+
return annotations_cache[service_class]
|
|
18
|
+
|
|
19
|
+
sig = inspect.signature(service_class.__init__)
|
|
20
|
+
hints = get_type_hints(service_class.__init__)
|
|
21
|
+
|
|
22
|
+
annotations = {}
|
|
23
|
+
for param_name, param in sig.parameters.items():
|
|
24
|
+
if param_name == "self":
|
|
25
|
+
continue
|
|
26
|
+
if param_name not in hints:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"Parameter '{param_name}' of {service_class.__name__} with type {param} is missing a type annotation"
|
|
29
|
+
)
|
|
30
|
+
annotations[param_name] = hints.get(param_name)
|
|
31
|
+
|
|
32
|
+
annotations_cache[service_class] = annotations
|
|
33
|
+
|
|
34
|
+
return annotations
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_annotations[T](cls: type[T], mandatory_params: list[str] | None = None):
|
|
38
|
+
"""Get annotations of a class instance."""
|
|
39
|
+
if cls in annotations_classes:
|
|
40
|
+
return annotations_classes[cls]
|
|
41
|
+
|
|
42
|
+
init_signature = inspect.signature(cls.__init__)
|
|
43
|
+
annotations = {}
|
|
44
|
+
|
|
45
|
+
for name, param in init_signature.parameters.items():
|
|
46
|
+
if name == "self":
|
|
47
|
+
continue
|
|
48
|
+
if param.annotation == inspect.Parameter.empty:
|
|
49
|
+
raise ValueError(f"Parameter {name} of {type(cls)} is missing a type annotation")
|
|
50
|
+
if param.default is not inspect.Parameter.empty:
|
|
51
|
+
pass
|
|
52
|
+
annotations[name] = param.annotation
|
|
53
|
+
|
|
54
|
+
if mandatory_params is not None:
|
|
55
|
+
missing_params = [param for param in mandatory_params if param not in annotations]
|
|
56
|
+
if missing_params:
|
|
57
|
+
raise ValueError(f"Missing required parameters: {', '.join(missing_params)}")
|
|
58
|
+
|
|
59
|
+
annotations_classes[cls] = annotations
|
|
60
|
+
return annotations
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def first_parameter_type(func):
|
|
64
|
+
"""Get the type of the first parameter of the function."""
|
|
65
|
+
signature = inspect.signature(func)
|
|
66
|
+
first_param = next(iter(signature.parameters.values())) # Get the first parameter
|
|
67
|
+
return first_param.annotation
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def get_base_type(annotated_type):
|
|
71
|
+
"""Extract the base type from an Annotated type."""
|
|
72
|
+
if hasattr(annotated_type, "__origin__"):
|
|
73
|
+
return annotated_type.__origin__
|
|
74
|
+
return annotated_type
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def function_parameters(func):
|
|
78
|
+
"""Get function parameters."""
|
|
79
|
+
signature = inspect.signature(func)
|
|
80
|
+
return signature.parameters
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def map_to_model(data: list[dict], model: type[BaseModel]) -> list[BaseModel]:
|
|
84
|
+
"""Map a list of dictionaries to a list of model instances."""
|
|
85
|
+
return [model(**item) for item in data]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def required_property(cls, name: str, default=None):
|
|
89
|
+
"""Create a required property for a class."""
|
|
90
|
+
if not hasattr(cls, "__annotations__"):
|
|
91
|
+
cls.__annotations__ = {}
|
|
92
|
+
cls.__annotations__[name] = default
|
|
93
|
+
return property(
|
|
94
|
+
lambda self: getattr(self, f"_{name}", default), lambda self, value: setattr(self, f"_{name}", value)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def map_data_to_model(df: pl.DataFrame, model: type[BaseModel]) -> list[BaseModel]:
|
|
99
|
+
"""Converts a Polars DataFrame to a list of Pydantic models.
|
|
100
|
+
|
|
101
|
+
Null values are handled automatically during conversion.
|
|
102
|
+
"""
|
|
103
|
+
df_clean = df.fill_nan(None)
|
|
104
|
+
|
|
105
|
+
return [model(**row) for row in df_clean.to_dicts()]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def enum_to_json_list(enum_class: type[Enum]) -> list[dict[str, str]]:
|
|
109
|
+
"""Convert enum class to JSON list format for frontend."""
|
|
110
|
+
return [{"id": item.name, "value": item.value} for item in enum_class]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Iterable
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def convert_nan_to_none(v):
|
|
6
|
+
"""If the value is NaN, convert it to None."""
|
|
7
|
+
if isinstance(v, float) and math.isnan(v):
|
|
8
|
+
return None
|
|
9
|
+
return v
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def to_list[T](value: Iterable[T] | None) -> list[T]:
|
|
13
|
+
"""Convert an iterable to a list, or return an empty list if None.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
value: The iterable to convert.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
A list containing the elements of the iterable, or an empty list if the input is None.
|
|
20
|
+
"""
|
|
21
|
+
if value is None:
|
|
22
|
+
return []
|
|
23
|
+
return list(value)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def to_set[T](value: Iterable[T] | None) -> set[T]:
|
|
27
|
+
"""Convert an iterable to a set, or return an empty set if None.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
value: The iterable to convert.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
A set containing the elements of the iterable, or an empty set if the input is None.
|
|
34
|
+
"""
|
|
35
|
+
if value is None:
|
|
36
|
+
return set()
|
|
37
|
+
return set(value)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
from sqlalchemy.engine.result import Row
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def convert_to_df(results: Any) -> pd.DataFrame:
|
|
9
|
+
"""Converts SQLAlchemy results to a pandas DataFrame."""
|
|
10
|
+
if hasattr(results, "keys"):
|
|
11
|
+
rows = results.fetchall()
|
|
12
|
+
return pd.DataFrame(rows, columns=results.keys())
|
|
13
|
+
|
|
14
|
+
if isinstance(results, list) and results:
|
|
15
|
+
if isinstance(results[0], Row):
|
|
16
|
+
return pd.DataFrame(results, columns=results[0].keys())
|
|
17
|
+
|
|
18
|
+
keys = results[0].keys() if isinstance(results[0], dict) else []
|
|
19
|
+
return pd.DataFrame(results, columns=keys)
|
|
20
|
+
|
|
21
|
+
raise ValueError("Unsupported result format for DataFrame conversion.")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def map_data_to_model(df: pd.DataFrame, model: type[BaseModel]) -> list[BaseModel]:
|
|
25
|
+
"""Converts a pandas DataFrame to a list of Pydantic models.
|
|
26
|
+
|
|
27
|
+
NaN values are replaced with None before instantiating the models.
|
|
28
|
+
"""
|
|
29
|
+
df = df.replace({float("nan"): None})
|
|
30
|
+
return [model(**row.to_dict()) for _, row in df.iterrows()]
|
fastspine/util/dates.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from datetime import datetime, timezone
|
|
2
|
+
|
|
3
|
+
from dateutil.relativedelta import relativedelta
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def is_date_in_future(date: datetime) -> bool:
|
|
7
|
+
"""Check if the provided date is in the future."""
|
|
8
|
+
if date.tzinfo is None:
|
|
9
|
+
date = date.replace(tzinfo=timezone.utc)
|
|
10
|
+
return date > datetime.now(timezone.utc)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def format_date(date: datetime, date_format: str = "%Y-%m-%d %H:%M:%S") -> str:
|
|
14
|
+
"""Format the date to a specific string format."""
|
|
15
|
+
return date.strftime(date_format) if date else ""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def now(timezone=timezone.utc) -> datetime:
|
|
19
|
+
"""Get the current date and time in UTC."""
|
|
20
|
+
return datetime.now(timezone)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def month_diff(start_date: datetime, end_date: datetime | None = None) -> int:
|
|
24
|
+
"""Calculate the difference in months between start_date and end_date (or now if None)."""
|
|
25
|
+
if start_date.tzinfo is None:
|
|
26
|
+
start_date = start_date.replace(tzinfo=timezone.utc)
|
|
27
|
+
|
|
28
|
+
if end_date is None:
|
|
29
|
+
end_date = datetime.now(timezone.utc)
|
|
30
|
+
elif end_date.tzinfo is None:
|
|
31
|
+
end_date = end_date.replace(tzinfo=timezone.utc)
|
|
32
|
+
|
|
33
|
+
delta = relativedelta(end_date, start_date)
|
|
34
|
+
return delta.years * 12 + delta.months
|