Python

Python Backend

Essential rules for Python API development

Python FastAPI Development
Python FastAPI Development Best Practices Comprehensive guide for building production-ready APIs with FastAPI, async Python, and modern backend development patterns. Project Structure Modular Application Architecture Organize code into logical modules (routers, models, schemas, services) Separate business logic from API logic Example structure: Configuration Management Use Pydantic BaseSettings for environment-based configuration Keep sensitive data in environment variables Implement different configs for development, testing, and production Example: Database Integration SQLAlchemy Async Patterns Use asyncio-compatible database drivers (asyncpg for PostgreSQL) Implement async session management Use select() for queries instead of legacy query() methods Example: Database Models and Relationships Define clear SQLAlchemy models with proper relationships Use appropriate column types and constraints Implement proper indexing for performance Example: Database Migrations Use Alembic for database schema migrations Create meaningful migration messages and version control Test migrations in development before applying to production Example migration workflow: Error Handling and Validation Custom Exception Handling Create custom exception classes for different error types Implement global exception handlers Return consistent error response formats Example: Input Validation Use Pydantic validators for complex validation logic Implement custom validators for business rules Provide clear error messages for validation failures Example: Testing Test Structure Write comprehensive unit tests for all business logic Implement integration tests for API endpoints Use pytest with async support for testing Example: Test Database Management Use separate test databases for isolation Implement database fixtures for test data Clean up test data after each test run Summary Checklist [ ] Use type hints and Pydantic models throughout [ ] Implement async/await for all I/O operations [ ] Structure project with clear separation of concerns [ ] Use dependency injection for shared logic [ ] Implement proper authentication and authorization [ ] Handle errors consistently with custom exceptions [ ] Optimize database queries and implement caching [ ] Write comprehensive tests for all functionality [ ] Use proper security headers and HTTPS [ ] Configure production deployment with Docker [ ] Implement monitoring and logging Follow these practices to build robust, scalable, and maintainable FastAPI applications.
Django REST Framework
Django REST Framework Best Practices Comprehensive guide for building robust, scalable REST APIs with Django REST Framework (DRF) and advanced Django patterns. Authentication and Permissions Authentication Strategy Implementation Configure multiple authentication backends Implement JWT authentication with refresh tokens Handle authentication errors gracefully Example authentication setup: Custom Permission Classes Create reusable permission classes Implement object-level permissions Handle complex permission logic Example permission implementations: Rate Limiting and Throttling Implement different throttle rates for different user types Create custom throttle classes Handle throttle exceeded scenarios Example throttling configuration: API Design and Documentation Versioning Strategy Implement API versioning Handle backward compatibility Provide clear migration paths Example versioning implementation: API Documentation with Swagger/OpenAPI Auto-generate API documentation Add detailed endpoint descriptions Include example requests and responses Example documentation setup: Production Deployment Security and Production Settings Configure proper security settings Implement CORS policies Set up proper logging and monitoring Example production configuration: Follow these practices to build robust, scalable, and maintainable REST APIs with Django REST Framework.
Python Asyncio & Asynchronous Programming
Python Asyncio This document provides comprehensive guidelines for python asyncio development and best practices. Coroutines & Tasks async async def function definitions Implement proper async def function definitions Follow best practices for optimal results await await expressions for suspension Implement proper await expressions for suspension Follow best practices for optimal results Task Task creation with create_task() Implement proper task creation with create_task() Follow best practices for optimal results Task Task cancellation and timeout handling Implement proper task cancellation and timeout handling Follow best practices for optimal results Exception Exception handling in coroutines Implement proper exception handling in coroutines Follow best practices for optimal results Concurrent Programming asyncio.gather() asyncio.gather() for parallel execution Implement proper asyncio.gather() for parallel execution Follow best practices for optimal results asyncio.wait() asyncio.wait() for completion handling Implement proper asyncio.wait() for completion handling Follow best practices for optimal results Semaphores Semaphores for resource limiting Implement proper semaphores for resource limiting Follow best practices for optimal results Locks Locks and synchronization primitives Implement proper locks and synchronization primitives Follow best practices for optimal results Queue Queue patterns for producer-consumer Implement proper queue patterns for producer-consumer Follow best practices for optimal results File I/O Operations aiofiles aiofiles for file operations Implement proper aiofiles for file operations Follow best practices for optimal results Asynchronous Asynchronous file reading/writing Implement proper asynchronous file reading/writing Follow best practices for optimal results Directory Directory operations Implement proper directory operations Follow best practices for optimal results Subprocess Subprocess management Implement proper subprocess management Follow best practices for optimal results Stream Stream processing Implement proper stream processing Follow best practices for optimal results Web Development FastAPI FastAPI for async web APIs Implement proper fastapi for async web apis Follow best practices for optimal results aiohttp aiohttp for web applications Implement proper aiohttp for web applications Follow best practices for optimal results WebSocket WebSocket handling Implement proper websocket handling Follow best practices for optimal results Middleware Middleware implementation Implement proper middleware implementation Follow best practices for optimal results Request/response Request/response streaming Implement proper request/response streaming Follow best practices for optimal results Performance Optimization Profiling Profiling async applications Implement proper profiling async applications Follow best practices for optimal results Memory Memory usage optimization Implement proper memory usage optimization Follow best practices for optimal results CPU-bound CPU-bound task handling Implement proper cpu-bound task handling Follow best practices for optimal results Backpressure Backpressure management Implement proper backpressure management Follow best practices for optimal results Resource Resource cleanup strategies Implement proper resource cleanup strategies Follow best practices for optimal results Advanced Patterns Context Context managers with async with Implement proper context managers with async with Follow best practices for optimal results Async Async generators and iterators Implement proper async generators and iterators Follow best practices for optimal results AsyncIterator AsyncIterator protocol implementation Implement proper asynciterator protocol implementation Follow best practices for optimal results Custom Custom awaitable objects Implement proper custom awaitable objects Follow best practices for optimal results Protocol-based Protocol-based programming Implement proper protocol-based programming Follow best practices for optimal results Production Considerations Event Event loop monitoring Implement proper event loop monitoring Follow best practices for optimal results Resource Resource leak detection Implement proper resource leak detection Follow best practices for optimal results Graceful Graceful shutdown handling Implement proper graceful shutdown handling Follow best practices for optimal results Process Process management Implement proper process management Follow best practices for optimal results Container Container deployment strategies Implement proper container deployment strategies Follow best practices for optimal results Summary Checklist [ ] Core principles implemented [ ] Best practices followed [ ] Performance optimized [ ] Security measures in place [ ] Testing strategy implemented [ ] Documentation completed [ ] Monitoring configured [ ] Production deployment ready Follow these comprehensive guidelines for successful python asyncio implementation.
PostgreSQL Database Development
Postgresql Advanced This document provides comprehensive guidelines for postgresql advanced development and best practices. Advanced SQL Window Window functions for analytical queries Implement proper window functions for analytical queries Follow best practices for optimal results Common Common Table Expressions (CTEs) Implement proper common table expressions (ctes) Follow best practices for optimal results Recursive Recursive queries Implement proper recursive queries Follow best practices for optimal results JSONB JSONB operations and indexing Implement proper jsonb operations and indexing Follow best practices for optimal results Full-text Full-text search capabilities Implement proper full-text search capabilities Follow best practices for optimal results Performance Optimization Query Query plan analysis with EXPLAIN Implement proper query plan analysis with explain Follow best practices for optimal results Index Index usage and optimization Implement proper index usage and optimization Follow best practices for optimal results Table Table partitioning strategies Implement proper table partitioning strategies Follow best practices for optimal results Connection Connection pooling with PgBouncer Implement proper connection pooling with pgbouncer Follow best practices for optimal results Query Query optimization techniques Implement proper query optimization techniques Follow best practices for optimal results Data Types & Features JSONB JSONB for semi-structured data Implement proper jsonb for semi-structured data Follow best practices for optimal results Arrays Arrays for list data Implement proper arrays for list data Follow best practices for optimal results UUID UUID for unique identifiers Implement proper uuid for unique identifiers Follow best practices for optimal results Geometric Geometric types for spatial data Implement proper geometric types for spatial data Follow best practices for optimal results Custom Custom enumerated types Implement proper custom enumerated types Follow best practices for optimal results Backup & Recovery pg_dump pg_dump for logical backups Implement proper pg_dump for logical backups Follow best practices for optimal results Continuous Continuous archiving with WAL Implement proper continuous archiving with wal Follow best practices for optimal results Point-in-time Point-in-time recovery (PITR) Implement proper point-in-time recovery (pitr) Follow best practices for optimal results Streaming Streaming replication setup Implement proper streaming replication setup Follow best practices for optimal results Backup Backup verification strategies Implement proper backup verification strategies Follow best practices for optimal results High Availability Master-slave Master-slave replication Implement proper master-slave replication Follow best practices for optimal results Streaming Streaming replication Implement proper streaming replication Follow best practices for optimal results Logical Logical replication Implement proper logical replication Follow best practices for optimal results Connection Connection failover Implement proper connection failover Follow best practices for optimal results Load Load balancing strategies Implement proper load balancing strategies Follow best practices for optimal results Advanced Features Materialized Materialized views for performance Implement proper materialized views for performance Follow best practices for optimal results Foreign Foreign data wrappers (FDW) Implement proper foreign data wrappers (fdw) Follow best practices for optimal results Table Table inheritance Implement proper table inheritance Follow best practices for optimal results Exclusion Exclusion constraints Implement proper exclusion constraints Follow best practices for optimal results Extensions Extensions and custom types Implement proper extensions and custom types Follow best practices for optimal results Follow these comprehensive guidelines for successful postgresql advanced implementation.
Redis Caching Strategies and Implementation
Redis Caching Strategies and Implementation Redis Setup and Configuration Basic Redis Configuration Docker Compose Setup Cache Client Implementation TypeScript Redis Client Cache-Aside Pattern Implementation Repository with Caching Layer Write-Through and Write-Behind Patterns Write-Through Cache Implementation Write-Behind Cache with Queue Advanced Caching Patterns Multi-Level Cache Implementation Cache Warming Strategy Redis Data Structures for Caching Advanced Data Structure Usage Cache Monitoring and Metrics Performance Monitoring Testing Cache Implementation Comprehensive Test Suite Production Optimization Memory and Performance Tuning Deployment and Scaling Redis Cluster Configuration Implementation Checklist [ ] Set up Redis server with production configuration [ ] Implement cache service with proper error handling [ ] Choose appropriate caching patterns (cache-aside, write-through, etc.) [ ] Design cache key naming strategy [ ] Implement cache warming for critical data [ ] Set up multi-level caching if needed [ ] Use Redis data structures for advanced use cases [ ] Implement cache monitoring and metrics [ ] Write comprehensive tests for cache functionality [ ] Configure Redis cluster for high availability [ ] Set up cache invalidation strategies [ ] Monitor cache hit ratios and performance metrics This guide provides a comprehensive foundation for implementing Redis caching strategies that can significantly improve application performance and scalability while maintaining data consistency and reliability.
Python Flask API Development
Python Flask API Development Project Structure and Organization Recommended Flask Project Structure Application Factory Pattern Configuration Management Environment-Based Configuration Database Models and Relationships SQLAlchemy Model Best Practices API Blueprint Structure RESTful API Blueprint Authentication and Authorization JWT Authentication Error Handling Custom Exception Classes Global Error Handler Input Validation and Serialization Request Validation with Marshmallow Testing Unit Tests with pytest Security Best Practices Security Headers and CORS Performance Optimization Database Query Optimization Checklist for Flask API Development [ ] Set up application factory pattern [ ] Configure environment-based settings [ ] Implement proper database models with relationships [ ] Create RESTful API blueprints [ ] Add JWT authentication and authorization [ ] Implement comprehensive error handling [ ] Add input validation and serialization [ ] Write unit and integration tests [ ] Configure security headers and CORS [ ] Implement rate limiting [ ] Optimize database queries [ ] Set up logging and monitoring [ ] Configure production deployment [ ] Document API endpoints