Skip to content

Python Backend Patterns

Accelerate Python backend development with Cursor IDE and Claude Code. These patterns cover web frameworks, data processing, machine learning integration, async programming, and deployment strategies tailored for AI-assisted Python development.

  1. Open Cursor in your workspace
  2. Launch Agent mode (Cmd/Ctrl + I)
  3. Prompt: “Create a Python project with:
    • FastAPI or Django framework
    • Poetry for dependency management
    • SQLAlchemy ORM
    • Pytest for testing
    • Pre-commit hooks
    • Docker configuration”
  4. Agent will set up the complete environment
# Cursor prompt for FastAPI setup:
"Create a FastAPI application with:
- Async/await support
- Pydantic models for validation
- JWT authentication
- Database integration with async SQLAlchemy
- OpenAPI documentation
- Background tasks with Celery"
# Generated structure:
app/
api/
v1/
endpoints/
dependencies/
core/
config.py
security.py
models/
schemas/
services/
db/
# Django REST Framework prompt:
"Set up Django REST API with:
- ViewSets and serializers
- Token authentication
- Pagination and filtering
- Custom permissions
- API versioning
- Swagger documentation"
# Database configuration prompt:
"Set up SQLAlchemy with:
- Declarative models
- Alembic migrations
- Connection pooling
- Session management
- Relationship mappings
- Query optimization"

Repository Pattern

# Prompt: "Implement repository pattern:
# - Abstract base repository
# - Concrete implementations
# - Unit of work pattern
# - Transaction management"

Database Sharding

# Prompt: "Add database sharding:
# - Horizontal partitioning
# - Shard routing
# - Cross-shard queries
# - Rebalancing strategy"
# Async implementation prompt:
"Create async Python service with:
- aiohttp for HTTP client
- asyncpg for PostgreSQL
- Redis with aioredis
- Concurrent task management
- Error handling for async
- Performance monitoring"
  1. Task Management: “Implement async task queue with priority”
  2. Connection Pooling: “Set up async connection pools”
  3. Rate Limiting: “Add async rate limiter”
  4. Testing: “Write async tests with pytest-asyncio”
# ETL pipeline prompt:
"Build ETL pipeline with:
- Data extraction from multiple sources
- Transformation with pandas
- Validation and cleaning
- Loading to data warehouse
- Error handling and retries
- Progress monitoring"
# Kafka processing:
"Implement Kafka consumer with:
- Message deserialization
- Processing logic
- Error handling
- Offset management
- Monitoring"
# ML serving prompt:
"Create ML model serving API with:
- Model loading and caching
- Preprocessing pipeline
- Batch prediction support
- A/B testing framework
- Model versioning
- Performance metrics"

AI-Assisted ML Ops

Cursor/Claude can help with:

  • Feature engineering pipelines
  • Model deployment strategies
  • Monitoring and alerting
  • Data drift detection
  • Model retraining automation
# Test suite prompt:
"Create comprehensive tests with:
- Unit tests with pytest
- Integration tests
- API contract tests
- Performance tests with locust
- Test fixtures and factories
- Coverage reporting"

Mocking Strategies

# Prompt: "Implement mocking for:
# - External API calls
# - Database queries
# - Time-dependent code
# - File system operations"

Property Testing

# Prompt: "Add property tests with:
# - Hypothesis strategies
# - Edge case generation
# - Stateful testing
# - Shrinking examples"
# Security implementation:
"Implement security layer with:
- OAuth2 with JWT tokens
- Role-based access control
- API key management
- Rate limiting per user
- Request signing
- Audit logging"
# Caching implementation:
"Add caching layer with:
- Redis for hot data
- Memcached for sessions
- Local LRU cache
- Cache warming strategies
- Invalidation patterns
- Distributed caching"
  1. Profiling: “Add code profiling with cProfile”
  2. APM Setup: “Configure New Relic or DataDog”
  3. Metrics: “Implement custom metrics with Prometheus”
  4. Optimization: “Optimize hot paths identified by profiling”
# Kubernetes deployment prompt:
"Create Kubernetes manifests for:
- Deployment with replicas
- Service and ingress
- ConfigMaps and secrets
- Horizontal pod autoscaling
- Health checks
- Resource limits"
# Python CI/CD prompt:
"Create GitHub Actions for:
- Linting with black/flake8
- Type checking with mypy
- Test execution
- Docker image build
- Deployment to K8s"
# Microservices prompt:
"Implement microservices communication with:
- gRPC for internal services
- REST for external APIs
- Service discovery
- Circuit breakers
- Distributed tracing
- Event sourcing"

Queue Patterns

Implement with AI assistance:

  • Celery for task queues
  • RabbitMQ for messaging
  • Event-driven architecture
  • Saga pattern for transactions
  • Dead letter queues
# Structure prompts like:
"Create [feature] in Python with:
- Type hints throughout
- Docstrings (Google style)
- Error handling
- Logging setup
- Unit tests
- Following PEP 8"

Code Review

Use AI to check:

  • PEP 8 compliance
  • Type hint coverage
  • Security vulnerabilities
  • Performance issues

Refactoring

AI can help with:

  • Extract method/class
  • Remove duplication
  • Optimize algorithms
  • Modernize syntax
# DDD implementation:
"Implement DDD patterns with:
- Aggregates and entities
- Value objects
- Domain services
- Repositories
- Domain events
- Bounded contexts"
# Event system prompt:
"Create event-driven system with:
- Event bus implementation
- Event storage
- Event replay
- Saga orchestration
- Eventually consistent updates"