tools2fast-fastapi 0.1.2__tar.gz → 0.1.3__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.
Files changed (31) hide show
  1. {tools2fast_fastapi-0.1.2/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.1.3}/PKG-INFO +1 -1
  2. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/pyproject.toml +1 -1
  3. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/__init__.py +7 -1
  4. tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/__version__.py +1 -0
  5. tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/schemas/__init__.py +13 -0
  6. tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/schemas/response_schema.py +282 -0
  7. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/__init__.py +2 -0
  8. tools2fast_fastapi-0.1.3/src/tools2fast_fastapi/services/transaction_service.py +67 -0
  9. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
  10. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/SOURCES.txt +2 -0
  11. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/__version__.py +0 -1
  12. tools2fast_fastapi-0.1.2/src/tools2fast_fastapi/schemas/__init__.py +0 -7
  13. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/LICENSE +0 -0
  14. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/MANIFEST.in +0 -0
  15. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/README.md +0 -0
  16. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/docs/guide.md +0 -0
  17. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/examples/example.py +0 -0
  18. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/setup.cfg +0 -0
  19. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/models/__init__.py +0 -0
  20. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/models/mixins.py +0 -0
  21. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/schemas/mixins.py +0 -0
  22. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
  23. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
  24. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/number_service.py +0 -0
  25. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi/services/revision_service.py +0 -0
  26. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
  27. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
  28. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
  29. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/tests/test_initial.py +0 -0
  30. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/tests/test_revision_service.py +0 -0
  31. {tools2fast_fastapi-0.1.2 → tools2fast_fastapi-0.1.3}/tests/test_schemas.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
5
5
  Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
6
6
  License: MIT License
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "tools2fast-fastapi"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,7 @@
1
1
  from .models.mixins import AuditMixin, IdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
2
+ from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService, TransactionService
3
+ from .schemas import APIResponse, BaseResponse, DataResponse, MessageResponse
2
4
  from . import schemas
3
- from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService
4
5
  from .__version__ import __version__
5
6
 
6
7
  __all__ = [
@@ -10,8 +11,13 @@ __all__ = [
10
11
  "NumberUniqueMixin",
11
12
  "RevisionMixin",
12
13
  "NumberMixin",
14
+ "APIResponse",
15
+ "BaseResponse",
16
+ "DataResponse",
17
+ "MessageResponse",
13
18
  "DocumentSimpleRevisionService",
14
19
  "DocumentWithItemsRevisionService",
20
+ "TransactionService",
15
21
  "schemas",
16
22
  "__version__",
17
23
  ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.3"
@@ -0,0 +1,13 @@
1
+ from .mixins import AuditMixin, IdMixin, TimestampMixin
2
+ from .response_schema import APIResponse, BaseResponse, DataResponse, ErrorResponse, MessageResponse
3
+
4
+ __all__ = [
5
+ "IdMixin",
6
+ "TimestampMixin",
7
+ "AuditMixin",
8
+ "APIResponse",
9
+ "BaseResponse",
10
+ "DataResponse",
11
+ "ErrorResponse",
12
+ "MessageResponse"
13
+ ]
@@ -0,0 +1,282 @@
1
+ """
2
+ Schemas de respuesta estándar para todos los endpoints.
3
+
4
+ Jerarquía de modelos:
5
+
6
+ BaseResponse
7
+ ├── MessageResponse → success/delete/create sin datos (data: None)
8
+ ├── DataResponse[T] → respuestas con payload tipado (data: T)
9
+ └── ErrorResponse → errores controlados e inesperados (data: None, success: False)
10
+
11
+ Factoría:
12
+ APIResponse → métodos estáticos que devuelven los modelos anteriores.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from typing import Any, Generic, TypeVar
19
+
20
+ from pydantic import BaseModel
21
+ from fastapi import status
22
+ from fastapi.responses import JSONResponse
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ T = TypeVar("T")
27
+
28
+
29
+ # ═══════════════════════════════════════════════════════
30
+ # Modelo auxiliar
31
+ # ═══════════════════════════════════════════════════════
32
+
33
+ class ErrorDetail(BaseModel):
34
+ """Información estructurada de un error."""
35
+
36
+ type: str
37
+ """Nombre de la clase de la excepción, p. ej. ``'ValueError'``."""
38
+
39
+ detail: str | None = None
40
+ """Mensaje de detalle. ``null`` en errores no controlados (seguridad)."""
41
+
42
+
43
+ # ═══════════════════════════════════════════════════════
44
+ # Jerarquía de respuesta
45
+ # ═══════════════════════════════════════════════════════
46
+
47
+ class BaseResponse(BaseModel):
48
+ """Estructura base compartida por todas las respuestas de la API.
49
+
50
+ Todos los endpoints devuelven exactamente estos cuatro campos::
51
+
52
+ {
53
+ "success": bool,
54
+ "message": str,
55
+ "error": {"type": str, "detail": str | null} | null,
56
+ "data": <T> | null
57
+ }
58
+ """
59
+
60
+ success: bool
61
+ message: str
62
+ error: ErrorDetail | None = None
63
+ data: Any = None
64
+
65
+
66
+ class MessageResponse(BaseResponse):
67
+ """Respuesta exitosa **sin** payload de datos.
68
+
69
+ Usada en: ``saved()``, ``deleted()``, ``created()`` sin argumento.
70
+ ``data`` está fijado en ``None`` — no admite payload.
71
+ """
72
+
73
+ success: bool = True
74
+ data: None = None
75
+
76
+
77
+ class DataResponse(BaseResponse, Generic[T]):
78
+ """Respuesta exitosa **con** payload de datos tipado.
79
+
80
+ Usada en: ``ok()``, ``created(data=…)``
81
+
82
+ Declara el tipo concreto en el decorador del endpoint::
83
+
84
+ response_model=DataResponse[QuotationHeaderRead]
85
+ response_model=DataResponse[list[ClientRead]]
86
+ """
87
+
88
+ success: bool = True
89
+ data: T # type: ignore[assignment]
90
+
91
+
92
+ class ErrorResponse(BaseResponse):
93
+ """Respuesta de error (controlado o inesperado).
94
+
95
+ ``success`` siempre es ``False``.
96
+ ``data`` siempre es ``null``.
97
+ """
98
+
99
+ success: bool = False
100
+ data: None = None
101
+
102
+
103
+ # ═══════════════════════════════════════════════════════
104
+ # Factoría
105
+ # ═══════════════════════════════════════════════════════
106
+
107
+ class APIResponse:
108
+ """Factoría de respuestas con tipado estricto para endpoints FastAPI.
109
+
110
+ Métodos de **éxito** → devuelven instancias Pydantic
111
+ (:class:`MessageResponse` / :class:`DataResponse`) que FastAPI serializa
112
+ y documenta automáticamente via ``response_model``.
113
+
114
+ Métodos de **error** → devuelven :class:`~fastapi.responses.JSONResponse`
115
+ porque necesitan ``status_code`` variable (400, 404, 500…).
116
+
117
+ Constante de clase:
118
+ ``ERROR_RESPONSES`` — dict listo para pasarse al ``APIRouter`` o a
119
+ cualquier decorador de endpoint::
120
+
121
+ router = APIRouter(responses=APIResponse.ERROR_RESPONSES)
122
+ """
123
+
124
+ ERROR_RESPONSES: dict = {
125
+ 400: {"model": ErrorResponse, "description": "Error controlado"},
126
+ 500: {"model": ErrorResponse, "description": "Error inesperado del servidor"},
127
+ }
128
+
129
+ # ─────────────────────────────────────────────────────────────────────────
130
+ # Éxito
131
+ # ─────────────────────────────────────────────────────────────────────────
132
+
133
+ @staticmethod
134
+ def ok(data: Any, *, message: str = "OK") -> DataResponse:
135
+ """Respuesta exitosa ``200`` con payload ``data``.
136
+
137
+ Args:
138
+ data: Objeto a devolver. Se serializa con ``.model_dump()``
139
+ automáticamente si es un modelo Pydantic.
140
+ message: Texto descriptivo. Por defecto ``"OK"``.
141
+
142
+ Example::
143
+
144
+ return APIResponse.ok(client)
145
+ return APIResponse.ok([item1, item2], message="Listado obtenido")
146
+ """
147
+ if hasattr(data, "model_dump"):
148
+ data = data.model_dump()
149
+ elif isinstance(data, list):
150
+ data = [
151
+ item.model_dump() if hasattr(item, "model_dump") else item
152
+ for item in data
153
+ ]
154
+ return DataResponse(message=message, data=data)
155
+
156
+ @staticmethod
157
+ def saved(*, message: str = "Guardado con éxito") -> MessageResponse:
158
+ """Respuesta ``200`` sin datos para PUT / PATCH.
159
+
160
+ Example::
161
+
162
+ return APIResponse.saved()
163
+ """
164
+ return MessageResponse(message=message)
165
+
166
+ @staticmethod
167
+ def created(
168
+ data: Any = None,
169
+ *,
170
+ message: str = "Creado con éxito",
171
+ ) -> MessageResponse | DataResponse:
172
+ """Respuesta ``201 Created``.
173
+
174
+ Sin ``data`` → :class:`MessageResponse` (solo mensaje).
175
+ Con ``data=`` → :class:`DataResponse` con el objeto serializado.
176
+
177
+ Example::
178
+
179
+ return APIResponse.created() # solo 201 + mensaje
180
+ return APIResponse.created(new_client) # 201 + objeto
181
+ """
182
+ if data is None:
183
+ return MessageResponse(message=message)
184
+ if hasattr(data, "model_dump"):
185
+ data = data.model_dump()
186
+ elif isinstance(data, list):
187
+ data = [
188
+ item.model_dump() if hasattr(item, "model_dump") else item
189
+ for item in data
190
+ ]
191
+ return DataResponse(message=message, data=data)
192
+
193
+ @staticmethod
194
+ def deleted(*, message: str = "Eliminado con éxito") -> MessageResponse:
195
+ """Respuesta ``200`` de confirmación de eliminación sin payload.
196
+
197
+ ``data`` siempre es ``null`` — no tiene sentido devolver el objeto
198
+ que ya no existe.
199
+
200
+ Example::
201
+
202
+ return APIResponse.deleted()
203
+ """
204
+ return MessageResponse(message=message)
205
+
206
+ # ─────────────────────────────────────────────────────────────────────────
207
+ # Error
208
+ # ─────────────────────────────────────────────────────────────────────────
209
+
210
+ @staticmethod
211
+ def fail(
212
+ message: str,
213
+ *,
214
+ error: str | dict | None = None,
215
+ status_code: int = status.HTTP_400_BAD_REQUEST,
216
+ ) -> JSONResponse:
217
+ """Error controlado **manual** desde el router.
218
+
219
+ Usar para validaciones que el router detecta antes de llamar al service
220
+ (ID inválido, permisos, etc.).
221
+
222
+ Args:
223
+ message: Mensaje legible para el usuario.
224
+ error: Detalle opcional: ``str`` o ``{"type": …, "detail": …}``.
225
+ status_code: Código HTTP. Por defecto ``400``.
226
+
227
+ Example::
228
+
229
+ return APIResponse.fail("ID inválido", status_code=422)
230
+ """
231
+ error_detail: ErrorDetail | None = None
232
+ if error is not None:
233
+ if isinstance(error, dict):
234
+ error_detail = ErrorDetail(**error)
235
+ else:
236
+ error_detail = ErrorDetail(type="Error", detail=str(error))
237
+
238
+ body = ErrorResponse(message=message, error=error_detail)
239
+ return JSONResponse(status_code=status_code, content=body.model_dump())
240
+
241
+ @staticmethod
242
+ def from_exception(
243
+ exc: Exception,
244
+ *,
245
+ controlled: tuple[type[Exception], ...] = (ValueError,),
246
+ status_code: int = status.HTTP_400_BAD_REQUEST,
247
+ ) -> JSONResponse:
248
+ """Convierte una excepción en un :class:`JSONResponse` estandarizado.
249
+
250
+ - **Controlada** → expone el mensaje al cliente y lo incluye en ``error.detail``.
251
+ - **No controlada** → mensaje genérico; ``error.detail`` oculto (seguridad);
252
+ traceback completo al logger.
253
+
254
+ Args:
255
+ exc: La excepción capturada.
256
+ controlled: Tipos "esperados". Por defecto ``(ValueError,)``.
257
+ status_code: Código HTTP para errores controlados.
258
+
259
+ Example::
260
+
261
+ try:
262
+ result = await TransactionService.run(session, ...)
263
+ return APIResponse.ok(result)
264
+ except Exception as exc:
265
+ return APIResponse.from_exception(exc)
266
+ """
267
+ error_detail = ErrorDetail(
268
+ type=type(exc).__name__,
269
+ detail=str(exc) if str(exc) else None,
270
+ )
271
+
272
+ if isinstance(exc, controlled):
273
+ body = ErrorResponse(message=str(exc), error=error_detail)
274
+ return JSONResponse(status_code=status_code, content=body.model_dump())
275
+
276
+ logger.exception("Error inesperado [%s]: %s", type(exc).__name__, exc)
277
+ error_detail.detail = None
278
+ body = ErrorResponse(message="Ha ocurrido un error", error=error_detail)
279
+ return JSONResponse(
280
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
281
+ content=body.model_dump(),
282
+ )
@@ -2,6 +2,7 @@ from .document_simple_revision_service import DocumentSimpleRevisionService
2
2
  from .document_with_items_revision_service import DocumentWithItemsRevisionService
3
3
  from .number_service import get_next_number
4
4
  from .revision_service import get_latest_revision, list_revisions, create_revision, clone_children
5
+ from .transaction_service import TransactionService
5
6
 
6
7
 
7
8
  __all__ = [
@@ -12,4 +13,5 @@ __all__ = [
12
13
  "list_revisions",
13
14
  "create_revision",
14
15
  "clone_children",
16
+ "TransactionService",
15
17
  ]
@@ -0,0 +1,67 @@
1
+ """
2
+ TransactionService
3
+
4
+ Servicio genérico que centraliza el manejo de transacciones de base de datos
5
+ (commit / rollback automático).
6
+
7
+ Para el manejo de respuestas HTTP usa :class:`~tenant.schemas.response_schema.APIResponse`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Awaitable, Callable, TypeVar
13
+
14
+ from sqlmodel.ext.asyncio.session import AsyncSession
15
+
16
+ T = TypeVar("T")
17
+
18
+
19
+ class TransactionService:
20
+ """Servicio genérico de transacciones para routers FastAPI."""
21
+
22
+ @staticmethod
23
+ async def run(
24
+ session: AsyncSession,
25
+ operation: Callable[[], Awaitable[T]],
26
+ ) -> T:
27
+ """Ejecuta ``operation`` y confirma la transacción.
28
+
29
+ Si ``operation`` lanza una excepción se hace rollback automático y se
30
+ re-lanza el error para que el llamador lo maneje con
31
+ :meth:`~tenant.schemas.response_schema.APIResponse.from_exception`.
32
+
33
+ Args:
34
+ session: Sesión asíncrona de SQLModel / SQLAlchemy.
35
+ operation: Coroutine factory sin argumentos que realiza las
36
+ operaciones de base de datos deseadas.
37
+
38
+ Returns:
39
+ El valor que devuelva ``operation``.
40
+
41
+ Raises:
42
+ Exception: La misma excepción lanzada dentro de ``operation``
43
+ tras ejecutar el rollback.
44
+
45
+ Example::
46
+
47
+ from tenant.schemas.response_schema import APIResponse
48
+ from tenant.services import TransactionService
49
+
50
+ @router.post("/")
51
+ async def create(data: MySchema, session: AsyncSession = Depends(...)):
52
+ try:
53
+ result = await TransactionService.run(
54
+ session,
55
+ lambda: my_db_function(session, data),
56
+ )
57
+ return APIResponse.created(result)
58
+ except Exception as exc:
59
+ return APIResponse.from_exception(exc)
60
+ """
61
+ try:
62
+ result = await operation()
63
+ await session.commit()
64
+ return result
65
+ except Exception:
66
+ await session.rollback()
67
+ raise
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tools2fast-fastapi
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Shared tools, mixins, and base services for FastAPI applications - Solautyc Team internal use
5
5
  Author-email: Angel Daniel Sanchez Castillo <angeldaniel.sanchezcastillo@gmail.com>
6
6
  License: MIT License
@@ -15,11 +15,13 @@ src/tools2fast_fastapi/models/__init__.py
15
15
  src/tools2fast_fastapi/models/mixins.py
16
16
  src/tools2fast_fastapi/schemas/__init__.py
17
17
  src/tools2fast_fastapi/schemas/mixins.py
18
+ src/tools2fast_fastapi/schemas/response_schema.py
18
19
  src/tools2fast_fastapi/services/__init__.py
19
20
  src/tools2fast_fastapi/services/document_simple_revision_service.py
20
21
  src/tools2fast_fastapi/services/document_with_items_revision_service.py
21
22
  src/tools2fast_fastapi/services/number_service.py
22
23
  src/tools2fast_fastapi/services/revision_service.py
24
+ src/tools2fast_fastapi/services/transaction_service.py
23
25
  tests/test_initial.py
24
26
  tests/test_revision_service.py
25
27
  tests/test_schemas.py
@@ -1 +0,0 @@
1
- __version__ = "0.1.2"
@@ -1,7 +0,0 @@
1
- from .mixins import AuditMixin, IdMixin, TimestampMixin
2
-
3
- __all__ = [
4
- "IdMixin",
5
- "TimestampMixin",
6
- "AuditMixin",
7
- ]