eco-back 0.1.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.
- eco_back/__init__.py +11 -0
- eco_back/api/__init__.py +9 -0
- eco_back/api/client.py +278 -0
- eco_back/api/config.py +58 -0
- eco_back/api/registro.py +91 -0
- eco_back/database/__init__.py +9 -0
- eco_back/database/config.py +58 -0
- eco_back/database/connection.py +198 -0
- eco_back/database/models.py +49 -0
- eco_back/database/postgis.py +350 -0
- eco_back/database/repository.py +152 -0
- eco_back-0.1.0.dist-info/METADATA +191 -0
- eco_back-0.1.0.dist-info/RECORD +16 -0
- eco_back-0.1.0.dist-info/WHEEL +5 -0
- eco_back-0.1.0.dist-info/licenses/LICENSE +21 -0
- eco_back-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Repositorio base para operaciones CRUD
|
|
3
|
+
"""
|
|
4
|
+
from typing import Generic, TypeVar, List, Optional, Dict, Any
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
|
|
7
|
+
from .connection import DatabaseConnection
|
|
8
|
+
from .models import BaseModel
|
|
9
|
+
|
|
10
|
+
T = TypeVar('T', bound=BaseModel)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BaseRepository(ABC, Generic[T]):
|
|
14
|
+
"""
|
|
15
|
+
Clase base para repositorios de base de datos
|
|
16
|
+
|
|
17
|
+
Implementa el patrón Repository para separar la lógica de acceso a datos
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, db_connection: DatabaseConnection):
|
|
21
|
+
"""
|
|
22
|
+
Inicializa el repositorio
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
db_connection: Conexión a la base de datos
|
|
26
|
+
"""
|
|
27
|
+
self.db = db_connection
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def table_name(self) -> str:
|
|
32
|
+
"""Nombre de la tabla en la base de datos"""
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def _row_to_model(self, row: Dict[str, Any]) -> T:
|
|
37
|
+
"""
|
|
38
|
+
Convierte una fila de la base de datos a un modelo
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
row: Fila de la base de datos
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
Instancia del modelo
|
|
45
|
+
"""
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def find_by_id(self, id: int) -> Optional[T]:
|
|
49
|
+
"""
|
|
50
|
+
Busca un registro por su ID
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
id: ID del registro
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
Instancia del modelo o None si no se encuentra
|
|
57
|
+
"""
|
|
58
|
+
query = f"SELECT * FROM {self.table_name} WHERE id = %s"
|
|
59
|
+
results = self.db.execute_query(query, (id,))
|
|
60
|
+
|
|
61
|
+
if results:
|
|
62
|
+
return self._row_to_model(results[0])
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
def find_all(self, limit: Optional[int] = None, offset: int = 0) -> List[T]:
|
|
66
|
+
"""
|
|
67
|
+
Obtiene todos los registros
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
limit: Número máximo de registros a retornar
|
|
71
|
+
offset: Número de registros a saltar
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
Lista de instancias del modelo
|
|
75
|
+
"""
|
|
76
|
+
query = f"SELECT * FROM {self.table_name}"
|
|
77
|
+
|
|
78
|
+
if limit:
|
|
79
|
+
query += f" LIMIT {limit} OFFSET {offset}"
|
|
80
|
+
|
|
81
|
+
results = self.db.execute_query(query)
|
|
82
|
+
return [self._row_to_model(row) for row in results]
|
|
83
|
+
|
|
84
|
+
def find_where(self, conditions: Dict[str, Any]) -> List[T]:
|
|
85
|
+
"""
|
|
86
|
+
Busca registros que cumplan ciertas condiciones
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
conditions: Diccionario con las condiciones (campo: valor)
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
Lista de instancias del modelo
|
|
93
|
+
"""
|
|
94
|
+
where_clauses = [f"{field} = %s" for field in conditions.keys()]
|
|
95
|
+
where_sql = " AND ".join(where_clauses)
|
|
96
|
+
|
|
97
|
+
query = f"SELECT * FROM {self.table_name} WHERE {where_sql}"
|
|
98
|
+
results = self.db.execute_query(query, tuple(conditions.values()))
|
|
99
|
+
|
|
100
|
+
return [self._row_to_model(row) for row in results]
|
|
101
|
+
|
|
102
|
+
@abstractmethod
|
|
103
|
+
def create(self, model: T) -> T:
|
|
104
|
+
"""
|
|
105
|
+
Crea un nuevo registro
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
model: Instancia del modelo a crear
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
Instancia del modelo creado con su ID
|
|
112
|
+
"""
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
@abstractmethod
|
|
116
|
+
def update(self, id: int, model: T) -> Optional[T]:
|
|
117
|
+
"""
|
|
118
|
+
Actualiza un registro existente
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
id: ID del registro a actualizar
|
|
122
|
+
model: Instancia del modelo con los nuevos datos
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
Instancia del modelo actualizado o None si no se encuentra
|
|
126
|
+
"""
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
def delete(self, id: int) -> bool:
|
|
130
|
+
"""
|
|
131
|
+
Elimina un registro por su ID
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
id: ID del registro a eliminar
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
True si se eliminó, False si no se encontró
|
|
138
|
+
"""
|
|
139
|
+
query = f"DELETE FROM {self.table_name} WHERE id = %s"
|
|
140
|
+
affected_rows = self.db.execute_update(query, (id,))
|
|
141
|
+
return affected_rows > 0
|
|
142
|
+
|
|
143
|
+
def count(self) -> int:
|
|
144
|
+
"""
|
|
145
|
+
Cuenta el número total de registros
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Número de registros en la tabla
|
|
149
|
+
"""
|
|
150
|
+
query = f"SELECT COUNT(*) as total FROM {self.table_name}"
|
|
151
|
+
result = self.db.execute_query(query)
|
|
152
|
+
return result[0]['total'] if result else 0
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: eco-back
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Librería Python eco-back
|
|
5
|
+
Author-email: EI UNP <ecosistema@unp.gov.co>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/tuusuario/eco-back
|
|
8
|
+
Project-URL: Documentation, https://github.com/tuusuario/eco-back
|
|
9
|
+
Project-URL: Repository, https://github.com/tuusuario/eco-back
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: psycopg2-binary>=2.9.0
|
|
23
|
+
Requires-Dist: geoalchemy2>=0.14.0
|
|
24
|
+
Requires-Dist: requests>=2.31.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
27
|
+
Requires-Dist: pytest-cov>=4.0; extra == "dev"
|
|
28
|
+
Requires-Dist: black>=23.0; extra == "dev"
|
|
29
|
+
Requires-Dist: flake8>=6.0; extra == "dev"
|
|
30
|
+
Requires-Dist: mypy>=1.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-mock>=3.12.0; extra == "dev"
|
|
32
|
+
Provides-Extra: geo
|
|
33
|
+
Requires-Dist: shapely>=2.0.0; extra == "geo"
|
|
34
|
+
Requires-Dist: geojson>=3.0.0; extra == "geo"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# eco-back
|
|
38
|
+
|
|
39
|
+
Librería Python para backend con soporte para PostgreSQL/PostGIS y clientes API
|
|
40
|
+
|
|
41
|
+
## Características
|
|
42
|
+
|
|
43
|
+
- ✅ **Base de datos**: Conexión y operaciones con PostgreSQL
|
|
44
|
+
- ✅ **PostGIS**: Operaciones geoespaciales (puntos, polígonos, búsquedas por proximidad)
|
|
45
|
+
- ✅ **Cliente API**: Cliente HTTP genérico y cliente específico UNP
|
|
46
|
+
- ✅ **Patrón Repository**: Implementación de patrones de diseño para acceso a datos
|
|
47
|
+
|
|
48
|
+
## Descripción
|
|
49
|
+
|
|
50
|
+
eco-back es una librería modular que facilita el desarrollo de aplicaciones backend, proporcionando abstracciones para bases de datos geoespaciales y consumo de APIs REST.
|
|
51
|
+
|
|
52
|
+
## Instalación
|
|
53
|
+
|
|
54
|
+
### Desde el código fuente
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install -e .
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Para desarrollo
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install -e ".[dev]"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Uso
|
|
67
|
+
|
|
68
|
+
### Cliente de Consecutivos (UNP)
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from eco_back.api import Consecutivo
|
|
72
|
+
|
|
73
|
+
# Crear cliente
|
|
74
|
+
client = Consecutivo(base_url="https://api.unp.example.com")
|
|
75
|
+
|
|
76
|
+
# Obtener consecutivo
|
|
77
|
+
consecutivo = client.obtener(origen=1)
|
|
78
|
+
if consecutivo:
|
|
79
|
+
print(f"Consecutivo: {consecutivo}")
|
|
80
|
+
|
|
81
|
+
client.close()
|
|
82
|
+
|
|
83
|
+
# Forma recomendada: usar context manager
|
|
84
|
+
with Consecutivo(base_url="https://api.unp.example.com") as client:
|
|
85
|
+
consecutivo = client.obtener(origen=1)
|
|
86
|
+
# Usar el consecutivo...
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Cliente API Genérico
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from eco_back.api import APIConfig, APIClient
|
|
93
|
+
|
|
94
|
+
config = APIConfig(
|
|
95
|
+
base_url="https://api.example.com",
|
|
96
|
+
timeout=30,
|
|
97
|
+
headers={"Authorization": "Bearer token"}
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
with APIClient(config) as client:
|
|
101
|
+
# GET request
|
|
102
|
+
data = client.get("/endpoint")
|
|
103
|
+
|
|
104
|
+
# POST request
|
|
105
|
+
result = client.post("/endpoint", json={"key": "value"})
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### Conexión básica a PostgreSQL
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from eco_back.database import DatabaseConfig, DatabaseConnection
|
|
112
|
+
|
|
113
|
+
config = DatabaseConfig(
|
|
114
|
+
host="localhost",
|
|
115
|
+
port=5432,
|
|
116
|
+
database="mi_base_datos",
|
|
117
|
+
user="usuario",
|
|
118
|
+
password="password"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
with DatabaseConnection(config) as db:
|
|
122
|
+
resultados = db.execute_query("SELECT * FROM tabla")
|
|
123
|
+
for row in resultados:
|
|
124
|
+
print(row)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Uso de PostGIS
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from eco_back.database import DatabaseConfig, DatabaseConnection, PostGISHelper
|
|
131
|
+
|
|
132
|
+
config = DatabaseConfig(
|
|
133
|
+
host="localhost",
|
|
134
|
+
port=5432,
|
|
135
|
+
database="mi_db_geo",
|
|
136
|
+
user="postgres",
|
|
137
|
+
password="password"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
with DatabaseConnection(config) as db:
|
|
141
|
+
postgis = PostGISHelper(db)
|
|
142
|
+
|
|
143
|
+
# Habilitar PostGIS
|
|
144
|
+
postgis.enable_postgis()
|
|
145
|
+
|
|
146
|
+
# Insertar un punto geográfico
|
|
147
|
+
punto_id = postgis.insert_point(
|
|
148
|
+
table_name="ubicaciones",
|
|
149
|
+
lat=40.4168,
|
|
150
|
+
lon=-3.7038,
|
|
151
|
+
data={"nombre": "Madrid", "tipo": "ciudad"}
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# Buscar puntos cercanos (5km)
|
|
155
|
+
cercanos = postgis.find_within_distance(
|
|
156
|
+
table_name="ubicaciones",
|
|
157
|
+
lat=40.4168,
|
|
158
|
+
lon=-3.7038,
|
|
159
|
+
distance_meters=5000
|
|
160
|
+
)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Desarrollo
|
|
164
|
+
|
|
165
|
+
### Ejecutar tests
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
pytest
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Formatear código
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
black src/ tests/
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Linting
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
flake8 src/ tests/
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Type checking
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
mypy src/
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Licencia
|
|
190
|
+
|
|
191
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
eco_back/__init__.py,sha256=wqxLfLLFexz8P2eytcAlniZpADuCEbcT5tYhEfvh280,181
|
|
2
|
+
eco_back/api/__init__.py,sha256=9moiU5H8jGlva8k65bUK49LRIkE7bcLH1SK1dk23wcM,202
|
|
3
|
+
eco_back/api/client.py,sha256=b2J9ty7mRtPUsMD-YJui60B9GEa-85VAAb-sS5y1Rp8,8537
|
|
4
|
+
eco_back/api/config.py,sha256=dyERZY_4lXtRjhqLaHI0F4WlgPOQ_sw35eHNWGkQNLo,1590
|
|
5
|
+
eco_back/api/registro.py,sha256=mQZXYnhkI_ETGmDJ8i1XrNTEsUX29q1mLvhJZDUybLU,2887
|
|
6
|
+
eco_back/database/__init__.py,sha256=Q11tisd_yRqiycXImDbXyZgr4C1ZiGM2E0Cawt1k7CE,251
|
|
7
|
+
eco_back/database/config.py,sha256=WTlQQoptL8RGRM_KIWcv9NJFXbDy_KVKvdykCrX47Rw,1584
|
|
8
|
+
eco_back/database/connection.py,sha256=wGafOl_0dpgtFeIwe1f6QBtyrQ2BiEbw50Yfs1E-RWA,6314
|
|
9
|
+
eco_back/database/models.py,sha256=832FKC-4lfWWai0b_mtCv-H1MdHLJaaFY5NvsW8BqGs,1161
|
|
10
|
+
eco_back/database/postgis.py,sha256=oTuz8OzGeFiM3Aro3Zlid31t7tJJNSvqAUYTTaYUzoI,10954
|
|
11
|
+
eco_back/database/repository.py,sha256=NFh0pfvf7Pw878qOoVhR8ARMFC0CiJBQ_EwKshY8lOE,4433
|
|
12
|
+
eco_back-0.1.0.dist-info/licenses/LICENSE,sha256=XKKSDU9WlUEAyPNlRhq6e2xhVNpJc097JwPZJ1rUnRE,1077
|
|
13
|
+
eco_back-0.1.0.dist-info/METADATA,sha256=k-MEYCgvA2RKFIT5tfeYR8C3LhRA2Ac2SFzlxTxm0VM,4615
|
|
14
|
+
eco_back-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
15
|
+
eco_back-0.1.0.dist-info/top_level.txt,sha256=ViJZv023782XNNFMcAsRC9iN1CU3tb8lP9wDAHacMyc,9
|
|
16
|
+
eco_back-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
eco_back
|