Este es el backend del proyecto POLI-PI, una API REST construida con FastAPI que proporciona servicios para la gestiΓ³n de noticias y autenticaciΓ³n de usuarios. El sistema permite a los administradores crear y gestionar noticias mientras que los usuarios pueden acceder a ellas de forma pΓΊblica.
| TecnologΓa | VersiΓ³n | PropΓ³sito |
|---|---|---|
| FastAPI | 0.104.1 | Framework web de alto rendimiento |
| Uvicorn | 0.24.0 | Servidor ASGI |
| SQLAlchemy | 2.0.23 | ORM para gestiΓ³n de base de datos |
| SQLite | - | Base de datos ligera |
| Passlib | 1.7.4 | Hashing de contraseΓ±as con bcrypt |
| Python-JOSE | 3.3.3 | Manejo de tokens JWT |
| Python-Multipart | 0.0.6 | Procesamiento de formularios |
poli-PI/
βββ backend/
β βββ __pycache__/
β βββ models/
β β βββ __init__.py
β β βββ user.py # Modelo de usuario
β β βββ noticia.py # Modelo de noticia
β βββ database.py # ConfiguraciΓ³n de base de datos
β βββ main.py # AplicaciΓ³n principal y rutas
β βββ requirements.txt # Dependencias del proyecto
βββ assets/
β βββ images/ # ImΓ‘genes del proyecto
βββ docs/ # DocumentaciΓ³n adicional
βββ README.md
βββ requirements.txt
| Campo | Tipo | Restricciones | DescripciΓ³n |
|---|---|---|---|
id |
Integer | Primary Key, Index | Identificador ΓΊnico |
username |
String(50) | Unique, Index, Not Null | Nombre de usuario |
password |
String(255) | Not Null | ContraseΓ±a hasheada |
| Campo | Tipo | Restricciones | DescripciΓ³n |
|---|---|---|---|
id |
Integer | Primary Key, Index | Identificador ΓΊnico |
titulo |
String(255) | Not Null | TΓtulo de la noticia |
contenido |
Text | Not Null | Contenido completo de la noticia |
imagen |
String(255) | Nullable | URL o ruta de la imagen |
- Protocolo: JWT (JSON Web Tokens)
- Algoritmo: HS256
- ** expiration_token**: 60 minutos
- Hashing de contraseΓ±as: Bcrypt
Usuario β POST /login β Credenciales vΓ‘lidas β JWT Token
β
Headers: Authorization: Bearer <token>
β
Accede a rutas protegidas
POST /login
Content-Type: application/x-www-form-urlencoded
username=admin&password=admin123Response (200 OK):
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}Response (401 Unauthorized):
{
"detail": "Credenciales incorrectas"
}GET /noticias/Response (200 OK):
[
{
"id": 1,
"titulo": "TΓtulo de la noticia",
"contenido": "Contenido completo de la noticia...",
"imagen": "/images/imagen.jpg"
}
]POST /noticias/
Authorization: Bearer <token>
Content-Type: application/json
{
"titulo": "Nueva Noticia",
"contenido": "Contenido de la noticia...",
"imagen": "/images/imagen.jpg"
}Response (200 OK):
{
"id": 2,
"titulo": "Nueva Noticia",
"contenido": "Contenido de la noticia...",
"imagen": "/images/imagen.jpg"
}POST /create_admin/Response (200 OK):
{
"message": "Admin user created",
"username": "admin",
"password": "admin123"
}Response (200 OK) - Si ya existe:
{
"message": "Admin user already exists"
}El backend sirve archivos estΓ‘ticos desde la carpeta /assets/images/:
GET /images/{nombre_archivo}
Ejemplo:
GET /images/poli-img-1.png
- Python 3.8+
- pip
git clone <repositorio-url>
cd poli-PIpython -m venv venv
source venv/bin/activate # En Linux/Mac
# o
venv\Scripts\activate # En Windowscd backend
pip install -r requirements.txtuvicorn main:app --reloadEl servidor estarΓ‘ disponible en: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
| Variable | Valor Actual | DescripciΓ³n |
|---|---|---|
SECRET_KEY |
"Tlou2301" | Clave secreta para JWT |
ALGORITHM |
"HS256" | Algoritmo de encriptaciΓ³n |
ACCESS_TOKEN_EXPIRE_MINUTES |
60 | Tiempo de expiraciΓ³n del token |
DATABASE_URL |
"sqlite:///./database.db" | URL de la base de datos |
β οΈ Nota: En producciΓ³n, mover estas variables a un archivo.envy usar valores seguros.
- UbicaciΓ³n:
backend/database.db - Tipo: SQLite (ligera, sin configuraciΓ³n adicional)
users- Almacena usuarios del sistemanoticias- Almacena las noticias
Las tablas se crean automΓ‘ticamente al iniciar la aplicaciΓ³n gracias a:
Base.metadata.create_all(bind=engine)app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Permite todos los orΓgenes
allow_credentials=True, # Permite credenciales
allow_methods=["*"], # Permite todos los mΓ©todos
allow_headers=["*"], # Permite todos los headers
)
β οΈ Seguridad: En producciΓ³n, reemplazarallow_origins=["*"]con los dominios especΓficos.
| Campo | Valor |
|---|---|
| Username | admin |
| Password | admin123 |
fastapi==0.104.1
uvicorn[standard]==0.24.0
python-multipart==0.0.6
sqlalchemy==2.0.23
passlib[bcrypt]==1.7.4
python-jose[cryptography]==3.3.3
python-multipart==0.0.6
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENTE β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β HTTP Requests
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β FASTAPI (main.py) β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β β ENDPOINTS β β
β β β’ POST /login β β
β β β’ GET /noticias/ β β
β β β’ POST /noticias/ (protegido) β β
β β β’ POST /create_admin/ β β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β β AUTENTICACIΓN JWT β β
β β β’ verify_password() β β
β β β’ create_token() β β
β β β’ get_current_user() β β
β βββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β SQLALCHEMY ORM β
β βββββββββββββββ ββββββββββββββββ β
β β User β β Noticia β β
β βββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β SQLite DB β
β backend/database.db β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
- AutenticaciΓ³n con OAuth2 - Integrar Google, Facebook, etc.
- Base de datos robusta - Migrar a PostgreSQL o MySQL
- Rate Limiting - Limitar solicitudes por IP
- Logging - Sistema de registro de eventos
- Unit Tests - Pruebas unitarias y de integraciΓ³n
- ValidaciΓ³n de datos - Uso de Pydantic models mΓ‘s robustos
- PaginaciΓ³n - Para endpoints con muchos resultados
- Upload de imΓ‘genes - Endpoint para subir imΓ‘genes
Este proyecto estΓ‘ bajo la Licencia MIT. Consulta el archivo docs/LICENSE para mΓ‘s detalles.
Desarrollado como parte del proyecto POLI-PI.
Para soporte, consulta la documentaciΓ³n en docs/deployment.md o crea un issue en el repositorio.
β¨οΈ Construido con β€οΈ usando FastAPI y Python
Β© 2025 Todos los derechos reservados.