tools2fast-fastapi 0.1.5__tar.gz → 0.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {tools2fast_fastapi-0.1.5/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.2.1}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/pyproject.toml +1 -1
- tools2fast_fastapi-0.2.1/src/tools2fast_fastapi/__init__.py +49 -0
- tools2fast_fastapi-0.2.1/src/tools2fast_fastapi/__version__.py +1 -0
- tools2fast_fastapi-0.2.1/src/tools2fast_fastapi/schemas/__init__.py +53 -0
- tools2fast_fastapi-0.2.1/src/tools2fast_fastapi/schemas/mixins.py +136 -0
- tools2fast_fastapi-0.2.1/src/tools2fast_fastapi/schemas/response_schema.py +383 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/utils/routing.py +2 -1
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1/src/tools2fast_fastapi.egg-info}/PKG-INFO +1 -1
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi.egg-info/SOURCES.txt +1 -0
- tools2fast_fastapi-0.2.1/tests/test_response_schema.py +275 -0
- tools2fast_fastapi-0.1.5/src/tools2fast_fastapi/__init__.py +0 -25
- tools2fast_fastapi-0.1.5/src/tools2fast_fastapi/__version__.py +0 -1
- tools2fast_fastapi-0.1.5/src/tools2fast_fastapi/schemas/__init__.py +0 -13
- tools2fast_fastapi-0.1.5/src/tools2fast_fastapi/schemas/mixins.py +0 -35
- tools2fast_fastapi-0.1.5/src/tools2fast_fastapi/schemas/response_schema.py +0 -310
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/LICENSE +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/MANIFEST.in +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/README.md +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/docs/guide.md +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/examples/example.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/setup.cfg +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/models/__init__.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/models/mixins.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/__init__.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/document_simple_revision_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/document_with_items_revision_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/number_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/revision_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/services/transaction_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/utils/__init__.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi.egg-info/dependency_links.txt +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi.egg-info/requires.txt +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi.egg-info/top_level.txt +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/tests/test_initial.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/tests/test_revision_service.py +0 -0
- {tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/tests/test_schemas.py +0 -0
{tools2fast_fastapi-0.1.5/src/tools2fast_fastapi.egg-info → tools2fast_fastapi-0.2.1}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
7
|
+
version = "0.2.1"
|
|
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"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from .models.mixins import AuditMixin, IdMixin, TimestampMixin, NumberUniqueMixin, RevisionMixin, NumberMixin
|
|
2
|
+
from .services import DocumentSimpleRevisionService, DocumentWithItemsRevisionService, TransactionService
|
|
3
|
+
from .schemas import (
|
|
4
|
+
APIResponse,
|
|
5
|
+
BaseSuccessResponse,
|
|
6
|
+
BaseControlledErrorResponse,
|
|
7
|
+
BaseUnexpectedErrorResponse,
|
|
8
|
+
BasePaymentRequiredResponse,
|
|
9
|
+
ErrorDetail,
|
|
10
|
+
SuccessResponseMixin,
|
|
11
|
+
ControlledErrorMixin,
|
|
12
|
+
UnexpectedErrorMixin,
|
|
13
|
+
PaymentRequiredMixin,
|
|
14
|
+
)
|
|
15
|
+
from .utils import SafeRouter
|
|
16
|
+
from . import schemas
|
|
17
|
+
from .__version__ import __version__
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
# Model mixins
|
|
21
|
+
"IdMixin",
|
|
22
|
+
"TimestampMixin",
|
|
23
|
+
"AuditMixin",
|
|
24
|
+
"NumberUniqueMixin",
|
|
25
|
+
"RevisionMixin",
|
|
26
|
+
"NumberMixin",
|
|
27
|
+
# Response models
|
|
28
|
+
"APIResponse",
|
|
29
|
+
"BaseSuccessResponse",
|
|
30
|
+
"BaseControlledErrorResponse",
|
|
31
|
+
"BaseUnexpectedErrorResponse",
|
|
32
|
+
"BasePaymentRequiredResponse",
|
|
33
|
+
# Error detail
|
|
34
|
+
"ErrorDetail",
|
|
35
|
+
# Response mixins
|
|
36
|
+
"SuccessResponseMixin",
|
|
37
|
+
"ControlledErrorMixin",
|
|
38
|
+
"UnexpectedErrorMixin",
|
|
39
|
+
"PaymentRequiredMixin",
|
|
40
|
+
# Utils
|
|
41
|
+
"SafeRouter",
|
|
42
|
+
# Services
|
|
43
|
+
"DocumentSimpleRevisionService",
|
|
44
|
+
"DocumentWithItemsRevisionService",
|
|
45
|
+
"TransactionService",
|
|
46
|
+
# Modules
|
|
47
|
+
"schemas",
|
|
48
|
+
"__version__",
|
|
49
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.1"
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from .mixins import (
|
|
2
|
+
AuditMixin,
|
|
3
|
+
IdMixin,
|
|
4
|
+
TimestampMixin,
|
|
5
|
+
NumberUniqueMixin,
|
|
6
|
+
RevisionMixin,
|
|
7
|
+
NumberMixin,
|
|
8
|
+
ErrorDetail,
|
|
9
|
+
SuccessResponseMixin,
|
|
10
|
+
ControlledErrorMixin,
|
|
11
|
+
UnexpectedErrorMixin,
|
|
12
|
+
PaymentRequiredMixin,
|
|
13
|
+
)
|
|
14
|
+
from .response_schema import (
|
|
15
|
+
APIResponse,
|
|
16
|
+
BaseSuccessResponse,
|
|
17
|
+
BaseControlledErrorResponse,
|
|
18
|
+
BaseUnexpectedErrorResponse,
|
|
19
|
+
BasePaymentRequiredResponse,
|
|
20
|
+
# Legacy classes (para backwards compatibility durante migración)
|
|
21
|
+
BaseResponse,
|
|
22
|
+
MessageResponse,
|
|
23
|
+
DataResponse,
|
|
24
|
+
ErrorResponse,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
# Model mixins
|
|
29
|
+
"IdMixin",
|
|
30
|
+
"TimestampMixin",
|
|
31
|
+
"AuditMixin",
|
|
32
|
+
"NumberUniqueMixin",
|
|
33
|
+
"RevisionMixin",
|
|
34
|
+
"NumberMixin",
|
|
35
|
+
# Error detail
|
|
36
|
+
"ErrorDetail",
|
|
37
|
+
# Response mixins
|
|
38
|
+
"SuccessResponseMixin",
|
|
39
|
+
"ControlledErrorMixin",
|
|
40
|
+
"UnexpectedErrorMixin",
|
|
41
|
+
"PaymentRequiredMixin",
|
|
42
|
+
# Response models
|
|
43
|
+
"APIResponse",
|
|
44
|
+
"BaseSuccessResponse",
|
|
45
|
+
"BaseControlledErrorResponse",
|
|
46
|
+
"BaseUnexpectedErrorResponse",
|
|
47
|
+
"BasePaymentRequiredResponse",
|
|
48
|
+
# Legacy classes (para backwards compatibility)
|
|
49
|
+
"BaseResponse",
|
|
50
|
+
"MessageResponse",
|
|
51
|
+
"DataResponse",
|
|
52
|
+
"ErrorResponse",
|
|
53
|
+
]
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel
|
|
5
|
+
from sqlmodel import SQLModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
9
|
+
# ERROR DETAIL — estructurado
|
|
10
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ErrorDetail(BaseModel):
|
|
14
|
+
"""Información estructurada de un error.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
type: Nombre de la clase de la excepción (e.g., ``'ValueError'``).
|
|
18
|
+
detail: Mensaje de detalle. ``None`` en errores no controlados (seguridad).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
type: str
|
|
22
|
+
detail: str | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
26
|
+
# RESPONSE MIXINS — Pydantic BaseModels para herencia
|
|
27
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SuccessResponseMixin(BaseModel):
|
|
31
|
+
"""Mixin para respuestas exitosas.
|
|
32
|
+
|
|
33
|
+
Los proyectos pueden heredar de esta clase para agregar los fields
|
|
34
|
+
``success`` y ``message`` a sus modelos de respuesta.
|
|
35
|
+
|
|
36
|
+
Example::
|
|
37
|
+
|
|
38
|
+
class ClientResponse(ClientRead, SuccessResponseMixin):
|
|
39
|
+
'''Respuesta exitosa para GET /clients/{id}'''
|
|
40
|
+
pass
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
success: Literal[True] = True
|
|
44
|
+
message: str = "Éxito"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ControlledErrorMixin(BaseModel):
|
|
48
|
+
"""Mixin para errores controlados (fail).
|
|
49
|
+
|
|
50
|
+
Attributes:
|
|
51
|
+
success: Siempre ``False``.
|
|
52
|
+
error_type: Siempre ``"controlled"``.
|
|
53
|
+
message: Mensaje legible para el usuario.
|
|
54
|
+
error: Detalle estructurado del error.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
success: Literal[False] = False
|
|
58
|
+
error_type: Literal["controlled"] = "controlled"
|
|
59
|
+
message: str
|
|
60
|
+
error: ErrorDetail | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class UnexpectedErrorMixin(BaseModel):
|
|
64
|
+
"""Mixin para errores inesperados (from_exception).
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
success: Siempre ``False``.
|
|
68
|
+
error_type: Siempre ``"unexpected"``.
|
|
69
|
+
message: Siempre ``"Ha ocurrido un error"``.
|
|
70
|
+
error: Detalle estructurado (detail oculto en producción).
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
success: Literal[False] = False
|
|
74
|
+
error_type: Literal["unexpected"] = "unexpected"
|
|
75
|
+
message: str = "Ha ocurrido un error"
|
|
76
|
+
error: ErrorDetail | None = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class PaymentRequiredMixin(BaseModel):
|
|
80
|
+
"""Mixin para errores de subscripción vencida (payment_required).
|
|
81
|
+
|
|
82
|
+
Attributes:
|
|
83
|
+
success: Siempre ``False``.
|
|
84
|
+
error_type: Siempre ``"payment_required"``.
|
|
85
|
+
message: Siempre ``"Pago requerido"``.
|
|
86
|
+
error: Detalle estructurado del error.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
success: Literal[False] = False
|
|
90
|
+
error_type: Literal["payment_required"] = "payment_required"
|
|
91
|
+
message: str = "Pago requerido"
|
|
92
|
+
error: ErrorDetail | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
96
|
+
# MODEL MIXINS — para SQLModel (recursos de base de datos)
|
|
97
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class IdMixin(SQLModel):
|
|
101
|
+
"""Schema mixin para recursos que tienen un ID entero."""
|
|
102
|
+
|
|
103
|
+
id: int
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TimestampMixin(SQLModel):
|
|
107
|
+
"""Schema mixin para recursos que incluyen timestamps de creación y actualización."""
|
|
108
|
+
|
|
109
|
+
created_at: datetime
|
|
110
|
+
updated_at: datetime
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class AuditMixin(SQLModel):
|
|
114
|
+
"""Schema mixin para recursos que incluyen IDs de usuario auditables."""
|
|
115
|
+
|
|
116
|
+
created_by: int | None = None
|
|
117
|
+
updated_by: int | None = None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class NumberMixin(SQLModel):
|
|
121
|
+
"""Schema mixin para recursos que usan un número de secuencia continuo."""
|
|
122
|
+
|
|
123
|
+
number: int
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class RevisionMixin(NumberMixin):
|
|
127
|
+
"""Schema mixin para recursos que incluyen número de revisión."""
|
|
128
|
+
|
|
129
|
+
revision: int
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class NumberUniqueMixin(SQLModel):
|
|
133
|
+
"""Schema mixin para recursos con número único por tenant."""
|
|
134
|
+
|
|
135
|
+
number: int
|
|
136
|
+
tenant_id: int
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Schemas de respuesta estándar para todos los endpoints.
|
|
3
|
+
|
|
4
|
+
Jerarquía de modelos (Phase 1: Unified API Responses):
|
|
5
|
+
|
|
6
|
+
BaseSuccessResponse → HTTP 200/201, success: true
|
|
7
|
+
BaseControlledErrorResponse → HTTP 400/404/etc, success: false, error_type: "controlled"
|
|
8
|
+
BaseUnexpectedErrorResponse → HTTP 500, success: false, error_type: "unexpected"
|
|
9
|
+
BasePaymentRequiredResponse → HTTP 402, success: false, error_type: "payment_required"
|
|
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, Literal, TypeVar
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel
|
|
21
|
+
from fastapi import status
|
|
22
|
+
|
|
23
|
+
from tools2fast_fastapi.schemas.mixins import (
|
|
24
|
+
ErrorDetail,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
T = TypeVar("T")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
33
|
+
# RESPUESTAS — Phase 1: Unified API Responses
|
|
34
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BaseSuccessResponse(BaseModel):
|
|
38
|
+
"""Respuesta exitosa con payload data (200/201).
|
|
39
|
+
|
|
40
|
+
Attributes:
|
|
41
|
+
success: Siempre ``True``.
|
|
42
|
+
message: Mensaje descriptivo. Por defecto ``"Éxito"``.
|
|
43
|
+
data: Payload con los datos de respuesta.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
success: Literal[True] = True
|
|
47
|
+
message: str = "Éxito"
|
|
48
|
+
data: Any = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BaseControlledErrorResponse(BaseModel):
|
|
52
|
+
"""Respuesta de error controlado (400/404/etc).
|
|
53
|
+
|
|
54
|
+
Para errores de validación de negocio, recursos no encontrados, etc.
|
|
55
|
+
|
|
56
|
+
Attributes:
|
|
57
|
+
success: Siempre ``False``.
|
|
58
|
+
error_type: Siempre ``"controlled"``.
|
|
59
|
+
message: Mensaje legible para el usuario.
|
|
60
|
+
error: Detalle estructurado del error.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
success: Literal[False] = False
|
|
64
|
+
error_type: Literal["controlled"] = "controlled"
|
|
65
|
+
message: str
|
|
66
|
+
error: ErrorDetail | None = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class BaseUnexpectedErrorResponse(BaseModel):
|
|
70
|
+
"""Respuesta de error inesperado del servidor (500).
|
|
71
|
+
|
|
72
|
+
Para errores no manejados que no deberían ocurrir en producción.
|
|
73
|
+
|
|
74
|
+
Attributes:
|
|
75
|
+
success: Siempre ``False``.
|
|
76
|
+
error_type: Siempre ``"unexpected"``.
|
|
77
|
+
message: Siempre ``"Ha ocurrido un error"`` (para no exponer detalles).
|
|
78
|
+
error: Detalle estructurado (detail oculto en producción).
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
success: Literal[False] = False
|
|
82
|
+
error_type: Literal["unexpected"] = "unexpected"
|
|
83
|
+
message: str = "Ha ocurrido un error"
|
|
84
|
+
error: ErrorDetail | None = None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class BasePaymentRequiredResponse(BaseModel):
|
|
88
|
+
"""Respuesta de pago requerido (402).
|
|
89
|
+
|
|
90
|
+
Cuando el usuario tiene la subscripción vencida.
|
|
91
|
+
|
|
92
|
+
Attributes:
|
|
93
|
+
success: Siempre ``False``.
|
|
94
|
+
error_type: Siempre ``"payment_required"``.
|
|
95
|
+
message: Mensaje legible para el usuario.
|
|
96
|
+
error: Detalle estructurado del error.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
success: Literal[False] = False
|
|
100
|
+
error_type: Literal["payment_required"] = "payment_required"
|
|
101
|
+
message: str = "Pago requerido"
|
|
102
|
+
error: ErrorDetail | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# Rebuild models to resolve Literal forward references
|
|
106
|
+
BaseSuccessResponse.model_rebuild()
|
|
107
|
+
BaseControlledErrorResponse.model_rebuild()
|
|
108
|
+
BaseUnexpectedErrorResponse.model_rebuild()
|
|
109
|
+
BasePaymentRequiredResponse.model_rebuild()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
113
|
+
# FACTORÍA — APIResponse
|
|
114
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class APIResponse:
|
|
118
|
+
"""Factoría de respuestas con tipado estricto para endpoints FastAPI.
|
|
119
|
+
|
|
120
|
+
Métodos de **éxito** → devuelven instancias Pydantic
|
|
121
|
+
(:class:`BaseSuccessResponse`) que FastAPI serializa y documenta
|
|
122
|
+
automáticamente via ``response_model``.
|
|
123
|
+
|
|
124
|
+
Métodos de **error** → devuelven tuplas ``(Model, status_code)`` para
|
|
125
|
+
permitir que el router establezca el código HTTP correcto mientras
|
|
126
|
+
mantiene tipado Pydantic en el cuerpo de la respuesta.
|
|
127
|
+
|
|
128
|
+
Constante de clase:
|
|
129
|
+
``ERROR_RESPONSES`` — dict listo para pasarse al ``APIRouter`` o a
|
|
130
|
+
cualquier decorador de endpoint::
|
|
131
|
+
|
|
132
|
+
router = APIRouter(responses=APIResponse.ERROR_RESPONSES)
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
ERROR_RESPONSES: dict = {
|
|
136
|
+
400: {"model": BaseControlledErrorResponse, "description": "Error controlado"},
|
|
137
|
+
402: {"model": BasePaymentRequiredResponse, "description": "Pago requerido"},
|
|
138
|
+
404: {"model": BaseControlledErrorResponse, "description": "Recurso no encontrado"},
|
|
139
|
+
500: {"model": BaseUnexpectedErrorResponse, "description": "Error inesperado del servidor"},
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
143
|
+
# Éxito
|
|
144
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
@staticmethod
|
|
147
|
+
def ok(data: Any = None, *, message: str = "Éxito") -> BaseSuccessResponse:
|
|
148
|
+
"""Respuesta exitosa ``200``/``201`` con payload ``data``.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
data: Objeto a devolver. Se serializa con ``.model_dump()``
|
|
152
|
+
automáticamente si es un modelo Pydantic.
|
|
153
|
+
message: Texto descriptivo. Por defecto ``"Éxito"``.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
:class:`BaseSuccessResponse` — Pydantic model (no JSONResponse).
|
|
157
|
+
|
|
158
|
+
Example::
|
|
159
|
+
|
|
160
|
+
return APIResponse.ok(client)
|
|
161
|
+
return APIResponse.ok([item1, item2], message="Listado obtenido")
|
|
162
|
+
return APIResponse.ok(data, message="Cliente actualizado")
|
|
163
|
+
"""
|
|
164
|
+
if hasattr(data, "model_dump"):
|
|
165
|
+
data = data.model_dump()
|
|
166
|
+
elif isinstance(data, list):
|
|
167
|
+
data = [
|
|
168
|
+
item.model_dump() if hasattr(item, "model_dump") else item
|
|
169
|
+
for item in data
|
|
170
|
+
]
|
|
171
|
+
return BaseSuccessResponse(message=message, data=data)
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def saved(*, message: str = "Guardado con éxito") -> BaseSuccessResponse:
|
|
175
|
+
"""Respuesta ``200`` sin datos para PUT / PATCH.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
message: Texto descriptivo. Por defecto ``"Guardado con éxito"``.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
:class:`BaseSuccessResponse` con ``data: None``.
|
|
182
|
+
|
|
183
|
+
Example::
|
|
184
|
+
|
|
185
|
+
return APIResponse.saved()
|
|
186
|
+
return APIResponse.saved(message="Configuración actualizada")
|
|
187
|
+
"""
|
|
188
|
+
return BaseSuccessResponse(message=message, data=None)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def created(
|
|
192
|
+
data: Any = None,
|
|
193
|
+
*,
|
|
194
|
+
message: str = "Creado con éxito",
|
|
195
|
+
) -> BaseSuccessResponse:
|
|
196
|
+
"""Respuesta ``201 Created``.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
data: Objeto creado (opcional).
|
|
200
|
+
message: Texto descriptivo. Por defecto ``"Creado con éxito"``.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
:class:`BaseSuccessResponse` con los datos serializados.
|
|
204
|
+
|
|
205
|
+
Example::
|
|
206
|
+
|
|
207
|
+
return APIResponse.created() # solo 201 + mensaje
|
|
208
|
+
return APIResponse.created(new_client) # 201 + objeto
|
|
209
|
+
return APIResponse.created(new_client, message="Cliente registrado")
|
|
210
|
+
"""
|
|
211
|
+
if data is None:
|
|
212
|
+
return BaseSuccessResponse(message=message, data=None)
|
|
213
|
+
if hasattr(data, "model_dump"):
|
|
214
|
+
data = data.model_dump()
|
|
215
|
+
elif isinstance(data, list):
|
|
216
|
+
data = [
|
|
217
|
+
item.model_dump() if hasattr(item, "model_dump") else item
|
|
218
|
+
for item in data
|
|
219
|
+
]
|
|
220
|
+
return BaseSuccessResponse(message=message, data=data)
|
|
221
|
+
|
|
222
|
+
@staticmethod
|
|
223
|
+
def deleted(*, message: str = "Eliminado con éxito") -> BaseSuccessResponse:
|
|
224
|
+
"""Respuesta ``200`` de confirmación de eliminación sin payload.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
message: Texto descriptivo. Por defecto ``"Eliminado con éxito"``.
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
:class:`BaseSuccessResponse` con ``data: None``.
|
|
231
|
+
|
|
232
|
+
Example::
|
|
233
|
+
|
|
234
|
+
return APIResponse.deleted()
|
|
235
|
+
"""
|
|
236
|
+
return BaseSuccessResponse(message=message, data=None)
|
|
237
|
+
|
|
238
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
239
|
+
# Error
|
|
240
|
+
# ─────────────────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def fail(
|
|
244
|
+
message: str,
|
|
245
|
+
*,
|
|
246
|
+
status_code: int = status.HTTP_400_BAD_REQUEST,
|
|
247
|
+
) -> tuple[BaseControlledErrorResponse, int]:
|
|
248
|
+
"""Error controlado **manual** desde el router.
|
|
249
|
+
|
|
250
|
+
Usar para validaciones que el router detecta antes de llamar al service
|
|
251
|
+
(ID inválido, permisos, etc.).
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
message: Mensaje legible para el usuario.
|
|
255
|
+
status_code: Código HTTP. Por defecto ``400``.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
Tupla ``(BaseControlledErrorResponse, status_code)`` — el llamador
|
|
259
|
+
debe usar estos para construir la respuesta HTTP.
|
|
260
|
+
|
|
261
|
+
Example::
|
|
262
|
+
|
|
263
|
+
error_response, http_status = APIResponse.fail("ID inválido", status_code=422)
|
|
264
|
+
return JSONResponse(status_code=http_status, content=error_response.model_dump())
|
|
265
|
+
"""
|
|
266
|
+
error_detail = ErrorDetail(type="ControlledError", detail=message)
|
|
267
|
+
return BaseControlledErrorResponse(message=message, error=error_detail), status_code
|
|
268
|
+
|
|
269
|
+
@staticmethod
|
|
270
|
+
def payment_required(
|
|
271
|
+
message: str = "Pago requerido",
|
|
272
|
+
) -> tuple[BasePaymentRequiredResponse, int]:
|
|
273
|
+
"""Error 402 explícito cuando el usuario debe realizar un pago.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
message: Mensaje legible para el usuario.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Tupla ``(BasePaymentRequiredResponse, 402)``.
|
|
280
|
+
|
|
281
|
+
Example::
|
|
282
|
+
|
|
283
|
+
error_response, http_status = APIResponse.payment_required()
|
|
284
|
+
return JSONResponse(status_code=http_status, content=error_response.model_dump())
|
|
285
|
+
"""
|
|
286
|
+
error_detail = ErrorDetail(type="PaymentRequired", detail=message)
|
|
287
|
+
return BasePaymentRequiredResponse(message=message, error=error_detail), status.HTTP_402_PAYMENT_REQUIRED
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def from_exception(
|
|
291
|
+
exc: Exception,
|
|
292
|
+
*,
|
|
293
|
+
controlled: tuple[type[Exception], ...] = (ValueError,),
|
|
294
|
+
) -> tuple[BaseControlledErrorResponse | BaseUnexpectedErrorResponse, int]:
|
|
295
|
+
"""Convierte una excepción en un modelo de error estandarizado.
|
|
296
|
+
|
|
297
|
+
- **Controlada** (``ValueError`` y subclases) → expone el mensaje al
|
|
298
|
+
cliente y retorna 400.
|
|
299
|
+
- **No controlada** → mensaje genérico; ``error.detail`` oculto;
|
|
300
|
+
traceback completo al logger; retorna 500.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
exc: La excepción capturada.
|
|
304
|
+
controlled: Tipos "esperados". Por defecto ``(ValueError,)``.
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
Tupla ``(BaseControlledErrorResponse, 400)`` para errores
|
|
308
|
+
controlados, o ``(BaseUnexpectedErrorResponse, 500)`` para
|
|
309
|
+
errores inesperados.
|
|
310
|
+
|
|
311
|
+
Example::
|
|
312
|
+
|
|
313
|
+
try:
|
|
314
|
+
result = await TransactionService.run(session, ...)
|
|
315
|
+
return APIResponse.ok(result)
|
|
316
|
+
except Exception as exc:
|
|
317
|
+
return APIResponse.from_exception(exc)
|
|
318
|
+
"""
|
|
319
|
+
error_detail = ErrorDetail(
|
|
320
|
+
type=type(exc).__name__,
|
|
321
|
+
detail=str(exc) if str(exc) else None,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
if isinstance(exc, controlled):
|
|
325
|
+
# Controlled exceptions get 400 with exposed message
|
|
326
|
+
logger.debug("Controlled exception [%s]: %s", type(exc).__name__, exc)
|
|
327
|
+
return BaseControlledErrorResponse(
|
|
328
|
+
message=str(exc), error=error_detail
|
|
329
|
+
), status.HTTP_400_BAD_REQUEST
|
|
330
|
+
|
|
331
|
+
# Unexpected exceptions get 500 with hidden detail
|
|
332
|
+
logger.exception("Error inesperado [%s]: %s", type(exc).__name__, exc)
|
|
333
|
+
error_detail.detail = None
|
|
334
|
+
return BaseUnexpectedErrorResponse(error=error_detail), status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
338
|
+
# LEGACY CLASSES — para backwards compatibility durante migración
|
|
339
|
+
# ═══════════════════════════════════════════════════════════════════════════════
|
|
340
|
+
# WARNING: Estas clases serán removidas cuando todos los routers estén migrados.
|
|
341
|
+
# Por favor usa las nuevas clases Base*Response y los mixins.
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
class BaseResponse(BaseModel):
|
|
345
|
+
"""CLASE LEGACY — Usar BaseSuccessResponse en su lugar.
|
|
346
|
+
|
|
347
|
+
Estructura base compartida por todas las respuestas de la API.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
success: bool
|
|
351
|
+
message: str
|
|
352
|
+
error: ErrorDetail | None = None
|
|
353
|
+
data: Any = None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
class MessageResponse(BaseResponse):
|
|
357
|
+
"""CLASE LEGACY — Usar BaseSuccessResponse en su lugar.
|
|
358
|
+
|
|
359
|
+
Respuesta exitosa sin payload de datos.
|
|
360
|
+
"""
|
|
361
|
+
|
|
362
|
+
success: bool = True
|
|
363
|
+
data: None = None
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class DataResponse(BaseResponse, Generic[T]):
|
|
367
|
+
"""CLASE LEGACY — Usar BaseSuccessResponse en su lugar.
|
|
368
|
+
|
|
369
|
+
Respuesta exitosa con payload de datos tipado.
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
success: bool = True
|
|
373
|
+
data: T # type: ignore[assignment]
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
class ErrorResponse(BaseResponse):
|
|
377
|
+
"""CLASE LEGACY — Usar BaseControlledErrorResponse o BaseUnexpectedErrorResponse.
|
|
378
|
+
|
|
379
|
+
Respuesta de error (controlado o inesperado).
|
|
380
|
+
"""
|
|
381
|
+
|
|
382
|
+
success: bool = False
|
|
383
|
+
data: None = None
|
{tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1}/src/tools2fast_fastapi/utils/routing.py
RENAMED
|
@@ -30,7 +30,8 @@ def handle_exceptions(func: Callable) -> Callable:
|
|
|
30
30
|
try:
|
|
31
31
|
return await func(*args, **kwargs)
|
|
32
32
|
except Exception as exc:
|
|
33
|
-
|
|
33
|
+
error_response, http_status = APIResponse.from_exception(exc)
|
|
34
|
+
return JSONResponse(status_code=http_status, content=error_response.model_dump())
|
|
34
35
|
|
|
35
36
|
return wrapper
|
|
36
37
|
|
{tools2fast_fastapi-0.1.5 → tools2fast_fastapi-0.2.1/src/tools2fast_fastapi.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tools2fast-fastapi
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|