Local Development Guide¶
Development Environment Setup¶
Prerequisites¶
- Python 3.8+
- Node.js 16+
- Redis
- PostgreSQL
- Docker (optional)
IDE Setup¶
Recommended VSCode extensions: - Python - Pylance - ESLint - Prettier - Docker - Redis - PostgreSQL
Environment Configuration¶
-
Create development environment file:
cp .env.example .env.development -
Configure local services:
# Development Settings DEBUG=True ENVIRONMENT=development LOG_LEVEL=DEBUG # Database DB_HOST=localhost DB_PORT=5432 DB_NAME=alischain_dev DB_USER=alischain DB_PASSWORD=development # Redis REDIS_URL=redis://localhost:6379/0 # Blockchain Networks (Use local test networks) ETH_RPC_URL=http://localhost:8545 POLYGON_RPC_URL=http://localhost:8546 # Security (Development only) JWT_SECRET_KEY=development_secret ENCRYPTION_KEY=development_key
Development Workflow¶
1. Starting Development Environment¶
# Start services
./scripts/dev/start_services.sh
# Activate virtual environment
source venv/bin/activate # Linux/Mac
.\venv\Scripts\activate # Windows
# Start development server
python main.py
2. Code Style and Linting¶
# Run code formatters
black .
isort .
# Run linters
flake8
pylint app tests
# Run type checking
mypy app
3. Running Tests¶
# Run all tests
pytest
# Run specific test file
pytest tests/test_blockchain.py
# Run with coverage
pytest --cov=app tests/
4. Database Management¶
# Create new migration
alembic revision --autogenerate -m "description"
# Apply migrations
alembic upgrade head
# Rollback migration
alembic downgrade -1
Local Testing¶
1. Mock Services¶
- Use
docker-compose.test.ymlfor isolated test environment - Mock external services using
pytest-mock - Use
responseslibrary for HTTP mocking
2. Test Data¶
- Fixtures in
tests/fixtures/ - Factory patterns in
tests/factories/ - Sample blockchain data in
tests/data/
3. Testing Tools¶
- pytest for unit/integration tests
- Postman/Insomnia for API testing
- Web3.py for blockchain testing
Debugging¶
1. VSCode Debug Configuration¶
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "main.py",
"FLASK_ENV": "development"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
]
},
{
"name": "Python: Tests",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"-v",
"tests/"
]
}
]
}
2. Logging Configuration¶
# In app/core/logging.py
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
},
"detailed": {
"format": "%(asctime)s [%(levelname)s] %(name)s:%(lineno)d: %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "standard",
"level": "DEBUG"
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"filename": "logs/development.log",
"maxBytes": 10485760, # 10MB
"backupCount": 5,
"formatter": "detailed",
"level": "DEBUG"
}
},
"loggers": {
"": {
"handlers": ["console", "file"],
"level": "DEBUG"
}
}
}
Performance Profiling¶
1. Code Profiling¶
# Profile Python code
python -m cProfile -o output.prof main.py
snakeviz output.prof
# Memory profiling
mprof run main.py
mprof plot
2. Database Profiling¶
# Enable query logging
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
# Use SQLAlchemy stats
from sqlalchemy import event
from sqlalchemy.engine import Engine
import time
@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
conn.info.setdefault('query_start_time', []).append(time.time())
@event.listens_for(Engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
total = time.time() - conn.info['query_start_time'].pop(-1)
print(f"Query: {statement}\nTime: {total}")
Local Backup Procedures¶
1. Database Backups¶
# Backup script (backup_db.sh)
#!/bin/bash
BACKUP_DIR="backups/database"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
# Backup database
pg_dump alischain_dev > "$BACKUP_DIR/db_backup_$TIMESTAMP.sql"
# Compress backup
gzip "$BACKUP_DIR/db_backup_$TIMESTAMP.sql"
# Remove backups older than 7 days
find "$BACKUP_DIR" -name "db_backup_*.sql.gz" -mtime +7 -delete
2. Code Backups¶
# Backup script (backup_code.sh)
#!/bin/bash
BACKUP_DIR="backups/code"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
# Exclude unnecessary files
EXCLUDE_FILE="backup_exclude.txt"
cat > "$EXCLUDE_FILE" << EOL
*.pyc
__pycache__
*.log
logs/
venv/
node_modules/
.env*
EOL
# Create backup
tar --exclude-from="$EXCLUDE_FILE" -czf "$BACKUP_DIR/code_backup_$TIMESTAMP.tar.gz" .
# Remove backups older than 30 days
find "$BACKUP_DIR" -name "code_backup_*.tar.gz" -mtime +30 -delete
3. Automated Backup Schedule¶
# Add to crontab
0 1 * * * /path/to/alischain/scripts/backup_db.sh
0 2 * * * /path/to/alischain/scripts/backup_code.sh
Recommended Development Tools¶
1. Code Quality¶
- Black (code formatting)
- isort (import sorting)
- flake8 (linting)
- mypy (type checking)
- bandit (security linting)
2. Testing¶
- pytest (testing framework)
- pytest-cov (coverage reporting)
- pytest-mock (mocking)
- pytest-asyncio (async testing)
- factory_boy (test data generation)
3. Database¶
- alembic (migrations)
- pgcli (PostgreSQL CLI)
- DBeaver (database GUI)
4. API Development¶
- Postman/Insomnia (API testing)
- swagger-ui (API documentation)
- locust (load testing)
5. Monitoring¶
- prometheus (metrics)
- grafana (visualization)
- sentry (error tracking)
6. Development Utilities¶
- httpie (HTTP client)
- redis-cli (Redis CLI)
- docker-compose (container management)
- make (build automation)
Last update:
2024-12-08