Python - Entorno de Desarrollo¶
Guía completa para configurar un entorno de desarrollo Python para backend que permita a Claude Code trabajar eficazmente.
Requisitos del Sistema¶
| Componente | Versión Mínima | Recomendada |
|---|---|---|
| Python | 3.10 | 3.12+ |
| pip | 23.0 | Latest |
| Poetry/uv | Latest | Latest |
| VS Code | 1.80+ | Latest |
Instalación de Python¶
Windows¶
# Opción 1: Winget (recomendado)
winget install Python.Python.3.12
# Opción 2: Python.org installer
# https://www.python.org/downloads/
# Opción 3: pyenv-win (para múltiples versiones)
winget install pyenv-win
pyenv install 3.12.0
pyenv global 3.12.0
# Verificar instalación
python --version
pip --version
# Asegurar que pip está actualizado
python -m pip install --upgrade pip
macOS¶
# Homebrew (recomendado)
brew install python@3.12
# O usar pyenv para múltiples versiones
brew install pyenv
pyenv install 3.12.0
pyenv global 3.12.0
# Añadir a ~/.zshrc
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc
# Verificar
python3 --version
pip3 --version
Linux (Ubuntu/Debian)¶
# Python 3.12 desde deadsnakes PPA
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.12 python3.12-venv python3.12-dev
# Configurar como default
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1
# O usar pyenv
curl https://pyenv.run | bash
# Añadir a ~/.bashrc
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
pyenv install 3.12.0
pyenv global 3.12.0
Gestores de Dependencias¶
Poetry (Recomendado)¶
# Instalación
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -
# Linux/macOS
curl -sSL https://install.python-poetry.org | python3 -
# Verificar
poetry --version
# Configuración recomendada
poetry config virtualenvs.in-project true # .venv dentro del proyecto
poetry config virtualenvs.create true
# Crear nuevo proyecto
poetry new myproject
cd myproject
# O inicializar en proyecto existente
poetry init
# Instalar dependencias
poetry install
# Añadir dependencia
poetry add fastapi uvicorn
# Añadir dependencia de desarrollo
poetry add --group dev pytest pytest-cov black ruff
# Ejecutar comandos en el entorno virtual
poetry run python main.py
poetry run pytest
# Activar shell del entorno virtual
poetry shell
uv (Alternativa moderna - más rápido)¶
# Instalación
# Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# Linux/macOS
curl -LsSf https://astral.sh/uv/install.sh | sh
# Verificar
uv --version
# Crear entorno virtual
uv venv
# Activar
# Windows
.venv\Scripts\activate
# Linux/macOS
source .venv/bin/activate
# Instalar dependencias (compatible con pip)
uv pip install fastapi uvicorn sqlalchemy
# Desde requirements.txt
uv pip install -r requirements.txt
# Sincronizar con pyproject.toml
uv pip sync pyproject.toml
pip + venv (Clásico)¶
# Crear entorno virtual
python -m venv .venv
# Activar
# Windows
.venv\Scripts\activate
# Linux/macOS
source .venv/bin/activate
# Instalar dependencias
pip install -r requirements.txt
# Crear requirements.txt
pip freeze > requirements.txt
IDE y Extensiones¶
Visual Studio Code¶
# Extensiones obligatorias
code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension ms-python.debugpy
# Extensiones recomendadas
code --install-extension charliermarsh.ruff # Linter rápido
code --install-extension ms-python.black-formatter # Formateo
code --install-extension njpwerner.autodocstring # Docstrings
code --install-extension littlefoxteam.vscode-python-test-adapter
code --install-extension ms-toolsai.jupyter # Notebooks
# Para desarrollo web
code --install-extension mtxr.sqltools
code --install-extension mtxr.sqltools-driver-pg
settings.json recomendado:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
"python.formatting.provider": "none",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
}
},
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": ["tests"],
"python.analysis.typeCheckingMode": "basic"
}
PyCharm (Alternativa)¶
# Windows
winget install JetBrains.PyCharm.Professional
# o Community Edition
winget install JetBrains.PyCharm.Community
# macOS
brew install --cask pycharm
Frameworks Backend¶
FastAPI (Recomendado)¶
# Dependencias
poetry add fastapi "uvicorn[standard]" pydantic pydantic-settings
# Estructura típica
myapp/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app
│ ├── api/
│ │ ├── __init__.py
│ │ ├── deps.py # Dependencies
│ │ └── v1/
│ │ ├── __init__.py
│ │ └── endpoints/
│ ├── core/
│ │ ├── __init__.py
│ │ ├── config.py # Settings
│ │ └── security.py
│ ├── models/ # SQLAlchemy models
│ ├── schemas/ # Pydantic schemas
│ ├── crud/ # Database operations
│ └── db/
│ ├── __init__.py
│ └── session.py
├── tests/
├── alembic/ # Migrations
├── pyproject.toml
└── alembic.ini
Comandos comunes:
# Ejecutar servidor de desarrollo
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Con auto-reload
poetry run uvicorn app.main:app --reload
# Producción con Gunicorn
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
Django¶
# Dependencias
poetry add django djangorestframework psycopg2-binary
# Crear proyecto
django-admin startproject myproject .
python manage.py startapp myapp
# Comandos comunes
python manage.py runserver
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py shell
python manage.py test
Flask¶
# Dependencias
poetry add flask flask-sqlalchemy flask-migrate flask-cors
# Ejecutar
flask run --debug
# O
python app.py
Bases de Datos¶
SQLAlchemy + Alembic (ORM y Migraciones)¶
# Dependencias
poetry add sqlalchemy alembic psycopg2-binary asyncpg
# Inicializar Alembic
alembic init alembic
# Configurar alembic.ini
# sqlalchemy.url = postgresql://user:pass@localhost/dbname
# Crear migración
alembic revision --autogenerate -m "Initial migration"
# Aplicar migraciones
alembic upgrade head
# Revertir
alembic downgrade -1
# Ver historial
alembic history
PostgreSQL Driver¶
# Síncrono
poetry add psycopg2-binary # o psycopg2 (requiere compilación)
# Asíncrono (para FastAPI async)
poetry add asyncpg
Connection string:
# Síncrono
DATABASE_URL = "postgresql://user:password@localhost:5432/dbname"
# Asíncrono
DATABASE_URL = "postgresql+asyncpg://user:password@localhost:5432/dbname"
Redis¶
MongoDB¶
Testing¶
pytest (Recomendado)¶
# Dependencias
poetry add --group dev pytest pytest-cov pytest-asyncio httpx
# pytest.ini o pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "-v --tb=short"
# Ejecutar tests
pytest
# Con cobertura
pytest --cov=app --cov-report=html
# Tests específicos
pytest tests/test_users.py
pytest -k "test_create_user"
# Tests paralelos
poetry add --group dev pytest-xdist
pytest -n auto
Fixtures para FastAPI¶
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from httpx import AsyncClient
from app.main import app
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
async def async_client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
Linting y Formateo¶
Ruff (Recomendado - reemplaza flake8, isort, black)¶
# Instalar
poetry add --group dev ruff
# Configuración en pyproject.toml
[tool.ruff]
target-version = "py312"
line-length = 88
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # Pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
]
ignore = ["E501"] # line too long
[tool.ruff.lint.isort]
known-first-party = ["app"]
# Ejecutar
ruff check .
ruff check --fix .
ruff format .
Black (Alternativa para formateo)¶
mypy (Type Checking)¶
poetry add --group dev mypy
# pyproject.toml
[tool.mypy]
python_version = "3.12"
strict = true
ignore_missing_imports = true
# Ejecutar
mypy app/
Docker para Python¶
Dockerfile Típico¶
# Usar imagen oficial de Python
FROM python:3.12-slim
# Variables de entorno
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
# Instalar dependencias del sistema
RUN apt-get update && apt-get install -y \
gcc \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
# Copiar requirements primero (para cache de Docker)
COPY requirements.txt .
RUN pip install -r requirements.txt
# Copiar código
COPY . .
# Usuario no-root
RUN adduser --disabled-password --gecos '' appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Con Poetry¶
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
POETRY_VERSION=1.8.0 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_CREATE=false
ENV PATH="$POETRY_HOME/bin:$PATH"
RUN pip install poetry==$POETRY_VERSION
WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN poetry install --no-interaction --no-ansi --no-root --only main
COPY . .
RUN poetry install --no-interaction --no-ansi --only-root
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Docker Compose¶
version: '3.8'
services:
api:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/myapp
- REDIS_URL=redis://redis:6379
depends_on:
- db
- redis
volumes:
- .:/app # Para desarrollo con hot-reload
db:
image: postgres:16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: myapp
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:
Comandos que Claude Code Ejecutará¶
# Gestión de entorno virtual
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows
# Poetry
poetry install
poetry add <package>
poetry remove <package>
poetry run <command>
poetry shell
# pip
pip install -r requirements.txt
pip freeze > requirements.txt
# Ejecución
python main.py
uvicorn app.main:app --reload
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
# Testing
pytest
pytest --cov=app
pytest -v -k "test_name"
# Linting/Formateo
ruff check .
ruff format .
black .
mypy app/
# Migraciones (Alembic)
alembic init alembic
alembic revision --autogenerate -m "message"
alembic upgrade head
alembic downgrade -1
# Django
python manage.py runserver
python manage.py migrate
python manage.py makemigrations
python manage.py test
# Docker
docker build -t myapp .
docker run -p 8000:8000 myapp
docker compose up -d
Verificación del Entorno¶
#!/bin/bash
# verify-python-env.sh
echo "=== Verificación Entorno Python ==="
echo -e "\n--- Python ---"
python --version
python3 --version
echo -e "\n--- pip ---"
pip --version
echo -e "\n--- Poetry ---"
poetry --version 2>/dev/null || echo "Poetry no instalado"
echo -e "\n--- Entorno Virtual ---"
if [ -d ".venv" ]; then
echo "✓ .venv existe"
source .venv/bin/activate 2>/dev/null && echo "✓ Activado correctamente"
else
echo "✗ No hay entorno virtual en .venv"
fi
echo -e "\n--- PostgreSQL Client ---"
psql --version 2>/dev/null || echo "psql no encontrado"
echo -e "\n--- Herramientas de Desarrollo ---"
python -c "import ruff" 2>/dev/null && echo "✓ ruff" || echo "✗ ruff"
python -c "import pytest" 2>/dev/null && echo "✓ pytest" || echo "✗ pytest"
python -c "import black" 2>/dev/null && echo "✓ black" || echo "✗ black"
echo -e "\n=== Verificación Completa ==="
Troubleshooting¶
"No module named 'xxx'"¶
# Verificar que el entorno virtual está activado
which python # Debe apuntar a .venv
# Reinstalar dependencias
poetry install
# o
pip install -r requirements.txt
SSL Certificate Error al instalar paquetes¶
# Actualizar certificados
pip install --upgrade certifi
# Windows: actualizar pip
python -m pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org
psycopg2 no compila en Windows¶
Permisos de Poetry en Windows¶
# Añadir Poetry al PATH
$env:PATH += ";$env:APPDATA\pypoetry\venv\Scripts"
# O añadir permanentemente
[Environment]::SetEnvironmentVariable("PATH", $env:PATH + ";$env:APPDATA\pypoetry\venv\Scripts", "User")