Configuración local#

Guía para configurar Construbot en un entorno de desarrollo local sin Docker.

Nota

Considere Docker: Se recomienda la configuración de Docker para la mayoría de los desarrolladores. Utilice la configuración local si prefiere el desarrollo tradicional de Python o necesita integrarse con otros servicios locales.

Descripción general#

El desarrollo local requiere instalar y configurar:

  1. Pitón 3.9.17+

  2. PostgreSQL 12+

  3. Redis 6+

  4. Dependencias de Python

Creará un entorno virtual y ejecutará servicios directamente en su máquina.

Requisitos previos#

Requisitos del sistema#

Python 3.9.17 o superior:

# Check version
python3 --version
# Should show: Python 3.9.17 or higher

Instalación:

# macOS (using Homebrew)
brew install python@3.9

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install python3.9 python3.9-venv python3.9-dev

# Windows
# Download from: https://www.python.org/downloads/

PostgreSQL 12+:

# Check if installed
psql --version

Instalación:

# macOS
brew install postgresql@12
brew services start postgresql@12

# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib libpq-dev

# Windows
# Download from: https://www.postgresql.org/download/windows/

Redis 6+:

# Check if installed
redis-cli --version

Instalación:

# macOS
brew install redis
brew services start redis

# Ubuntu/Debian
sudo apt-get install redis-server
sudo systemctl start redis

# Windows
# Use WSL or download from: https://github.com/microsoftarchive/redis/releases

Herramientas de desarrollo#

Git:

git --version

pip y entorno virtual:

# Should be included with Python
pip3 --version
python3 -m venv --help

Pasos de instalación#

Paso 1: clonar repositorio#

git clone https://github.com/javier-llamas/construbot.git
cd construbot

Paso 2: crear un entorno virtual#

# Create virtual environment
python3.9 -m venv venv

# Activate virtual environment
# macOS/Linux:
source venv/bin/activate

# Windows:
venv\\Scripts\\activate

Su mensaje debería cambiar para mostrar (venv):

(venv) user@computer:~/construbot$

Nota

Recuerda activar: Debes activar el entorno virtual cada vez que trabajes en el proyecto. Agregue source venv/bin/activate a su perfil de shell para la activación automática.

Paso 3: instalar las dependencias de Python#

# Upgrade pip
pip install --upgrade pip

# Install local development dependencies
pip install -r requirements/local.txt

Esto instala:

  • Django 3.2.19 y todas las extensiones

  • Herramientas de desarrollo (pytest, cobertura, django-debug-toolbar)

  • Controladores de base de datos (psycopg2)

  • Todas las dependencias del proyecto.

Resultado esperado:

Collecting django==3.2.19
Collecting djangorestframework==3.13.1
...
Successfully installed ...

Verificar instalación:

python -c "import django; print(django.get_version())"
# Should show: 3.2.19

Paso 4: configurar la base de datos#

Crear base de datos PostgreSQL:

# Connect to PostgreSQL as superuser
# macOS/Linux:
psql postgres

# Ubuntu (if above doesn't work):
sudo -u postgres psql

En la consola PostgreSQL:

-- Create database
CREATE DATABASE construbot_dev;

-- Create user
CREATE USER construbot_user WITH PASSWORD 'construbot_pass';

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE construbot_dev TO construbot_user;

-- Exit
\\q

Verificar conexión:

psql -h localhost -U construbot_user -d construbot_dev
# Enter password: construbot_pass

Si tiene éxito, verá el mensaje de PostgreSQL. Escriba \\q para salir.

Paso 5: configurar las variables de entorno#

Crear archivo .env:

# Copy example file
cp .env.example .env

# Edit with your preferred editor
nano .env

Configuraciones requeridas para el desarrollo local:

# Django Settings
DJANGO_SETTINGS_MODULE=construbot.config.settings.local
DJANGO_DEBUG=True
DJANGO_READ_DOT_ENV_FILE=True
DJANGO_SECRET_KEY=your-secret-key-here-change-in-production

# Docker (set to no for local development)
USE_DOCKER=no

# Database
DATABASE_URL=postgresql://construbot_user:construbot_pass@localhost:5432/construbot_dev

# Redis
REDIS_URL=redis://localhost:6379/0

# Email (console backend for development)
DJANGO_EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend

Nota

Generar SECRET_KEY: Utilice el generador de claves secretas de Django:

python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

Alternativa: Usar exportaciones de entorno (temporal):

export DJANGO_SETTINGS_MODULE=construbot.config.settings.local
export DJANGO_DEBUG=True
export DATABASE_URL=postgresql://construbot_user:construbot_pass@localhost:5432/construbot_dev

Estos se pierden al cerrar el terminal.

Paso 6: ejecutar migraciones de bases de datos#

python manage.py migrate

Resultado esperado:

Operations to perform:
  Apply all migrations: account, account_config, admin, auth, contenttypes, ...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying users.0001_initial... OK
  ...

Verificar que se crearon las tablas:

psql -h localhost -U construbot_user -d construbot_dev -c "\\dt"

Deberías ver una lista de tablas de Django.

Paso 7: crear superusuario#

python manage.py createsuperuser

Indicaciones:

Email: admin@example.com
Password:
Password (again):
Superuser created successfully.

Nota

Correo electrónico como nombre de usuario: Construbot utiliza el correo electrónico para la autenticación, no los nombres de usuario tradicionales.

Paso 8: recopile archivos estáticos#

python manage.py collectstatic --no-input

Esto copia archivos estáticos (CSS, JavaScript, imágenes) al directorio staticfiles/.

Paso 9: ejecutar el servidor de desarrollo#

# Using Makefile (recommended)
make runserver

# Or manually:
python manage.py runserver

Resultado esperado:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 29, 2025 - 14:30:00
Django version 3.2.19, using settings 'construbot.config.settings.local'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Accede a la aplicación:

Abra http://localhost:8000 en su navegador e inicie sesión con sus credenciales de superusuario.

Flujo de trabajo de desarrollo#

Inicio diario#

# 1. Navigate to project
cd ~/construbot

# 2. Activate virtual environment
source venv/bin/activate

# 3. Start Redis (if not running as service)
redis-server &

# 4. Start PostgreSQL (if not running as service)
# macOS: brew services start postgresql
# Linux: sudo systemctl start postgresql

# 5. Run Django development server
make runserver

Migraciones de bases de datos#

Después de modificar modelos:

# Create migration files
python manage.py makemigrations

# Apply migrations
python manage.py migrate

Verificar estado migratorio:

python manage.py showmigrations

Concha Django#

python manage.py shell
>>> from construbot.users.models import User
>>> User.objects.all()
<QuerySet [<User: admin@example.com>]>

Comandos de gestión#

Rellenar datos de prueba:

python manage.py poblar

Crea otro superusuario:

python manage.py createsuperuser

Ejecutar comandos personalizados:

python manage.py <command_name>

Archivos estáticos#

Durante el desarrollo:

Django sirve archivos estáticos automáticamente con DEBUG=True. No se necesita ninguna acción.

Después de agregar/modificar archivos estáticos:

python manage.py collectstatic

Pruebas#

Ejecución de pruebas#

# Full test suite with coverage
make localtest

# Or manually:
pytest

# Run specific test file
pytest tests/test_users.py

# Run with coverage report
pytest --cov=construbot --cov-report=html

Ver informe de cobertura:

open htmlcov/index.html

Configuración de prueba#

Las pruebas locales utilizan construbot.config.settings.test que:

  • Utiliza una base de datos SQLite en memoria

  • Desactiva las migraciones para mayor velocidad.

  • Establece configuraciones específicas de prueba

Consulte /contributor/testing/running-tests para obtener más detalles.

Apio corriendo#

Para procesamiento de tareas en segundo plano:

Iniciar trabajador de apio:

# In a separate terminal
celery -A construbot.taskapp worker -l info

Tareas de seguimiento:

# Celery flower (task monitoring web UI)
pip install flower
celery -A construbot.taskapp flower

Acceda a Flower en http://localhost:5555

Gestión de bases de datos#

Base de datos de respaldo#

# Backup to SQL file
pg_dump -h localhost -U construbot_user construbot_dev > backup.sql

Restaurar base de datos#

# Drop existing database
psql postgres -c "DROP DATABASE construbot_dev;"

# Create fresh database
psql postgres -c "CREATE DATABASE construbot_dev;"

# Restore from backup
psql -h localhost -U construbot_user construbot_dev < backup.sql

Restablecer base de datos#

# Drop and recreate
psql postgres -c "DROP DATABASE construbot_dev;"
psql postgres -c "CREATE DATABASE construbot_dev;"
psql postgres -c "GRANT ALL PRIVILEGES ON DATABASE construbot_dev TO construbot_user;"

# Run migrations
python manage.py migrate

# Create superuser
python manage.py createsuperuser

Acceder a la consola de base de datos#

# PostgreSQL console
python manage.py dbshell

# Or directly:
psql -h localhost -U construbot_user -d construbot_dev

Solución de problemas#

Problemas del entorno virtual#

Error: «No hay módulo llamado “django”»

Causa: Entorno virtual no activado

Solución:

source venv/bin/activate
# Verify: which python should show path to venv

Error: «Comando “python” no encontrado»

Solución: Use python3 en lugar de python

Errores de conexión a la base de datos#

Error: «no se pudo conectar al servidor»

Solución 1: Verifique que PostgreSQL se esté ejecutando

# macOS
brew services list | grep postgresql

# Linux
sudo systemctl status postgresql

Solución 2: Verificar DATABASE_URL en .env

# Should match your database credentials
DATABASE_URL=postgresql://construbot_user:construbot_pass@localhost:5432/construbot_dev

Solución 3: Verifique que PostgreSQL acepte conexiones

psql -h localhost -U construbot_user -d construbot_dev

Si esto falla, verifique la configuración de pg_hba.conf.

Errores de conexión de Redis#

Error: «Error 111 al conectarse al host local:6379»

Solución: Iniciar Redis

# macOS
brew services start redis

# Linux
sudo systemctl start redis

# Verify:
redis-cli ping
# Should respond: PONG

Errores de permiso#

Error: «permiso denegado para crear una base de datos»

Solución: Otorgar privilegios al usuario de PostgreSQL

-- As PostgreSQL superuser
GRANT ALL PRIVILEGES ON DATABASE construbot_dev TO construbot_user;
ALTER USER construbot_user CREATEDB;

Errores de migración#

Error: «No se aplican migraciones»

Causa: Migraciones ya aplicadas

Verificar:

python manage.py showmigrations

Error: «La migración se aplica antes de su dependencia»

Solución: Restablecer migraciones (ADVERTENCIA: destruye datos)

# Drop database and start fresh
# See "Reset Database" section above

Puerto ya en uso#

Error: «Ese puerto ya está en uso»

Solución: Proceso de búsqueda y eliminación

# macOS/Linux
lsof -ti:8000 | xargs kill -9

# Or use different port
python manage.py runserver 8001

Consejos de desarrollo#

La recarga automática no funciona#

La recarga automática de Django debería reiniciarse con los cambios de código. Si no:

# Run with --noreload to disable (for debugging)
python manage.py runserver --noreload

# Check file watchers limit (Linux)
cat /proc/sys/fs/inotify/max_user_watches

Integración IDE#

PyCharm:

  1. Archivo → Configuración → Proyecto → Intérprete Python

  2. Agregar intérprete → Entorno existente

  3. Seleccione venv/bin/python

Código VS:

  1. Cmd+Shift+P → «Python: Seleccionar intérprete»

  2. Elija ./venv/bin/python

.vscode/settings.json:

{
  "python.pythonPath": "venv/bin/python",
  "python.linting.enabled": true,
  "python.linting.pylintEnabled": true,
  "python.formatting.provider": "black"
}

Alias ​​de shell#

Agregue a ~/.bashrc o ~/.zshrc:

# Construbot aliases
alias cbot='cd ~/construbot && source venv/bin/activate'
alias crun='python manage.py runserver'
alias cmigrate='python manage.py migrate'
alias cshell='python manage.py shell'

Luego usa:

cbot     # Navigate and activate
crun     # Run server
cmigrate # Run migrations

Actualización de dependencias#

Actualizar archivos de requisitos#

# Install pip-tools
pip install pip-tools

# Update compiled requirements
make pipcompile

# Sync your environment
pip-sync requirements/local.txt

Actualización manual#

# Update specific package
pip install --upgrade django

# Update all packages (be careful!)
pip list --outdated
pip install --upgrade <package-name>

# Freeze new versions
pip freeze > requirements/local.txt

Después de la actualización#

# Run migrations
python manage.py migrate

# Run tests
make localtest

# Check for deprecation warnings
python -Wd manage.py runserver

Próximos pasos#

Después de una instalación exitosa:

  1. Rellenar datos de prueba: python administrar.py poblar

  2. Explore el código base: Descripción general

  3. Leer documentos API: API

  4. Verifique el flujo de trabajo de desarrollo: /contributor/development-setup

Ver también#