Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
@@ -0,0 +1,202 @@
---
description: Comprehensive guide to Django best practices covering code organization, performance, security, testing, and common pitfalls. This rule ensures adherence to community standards for maintainable and efficient Django applications.
globs: **/*.py
---
# Django Best Practices and Coding Standards
This guide outlines best practices for developing Django applications to ensure code quality, maintainability, performance, and security.
## 1. Code Organization and Structure
- **Directory Structure:**
- **Project Root:** Manage.py, settings, urls, wsgi.
- **Apps:** Each app should reside in its own directory.
- **Static Files:** Separate directory for static files (CSS, JavaScript, images).
- **Templates:** Dedicated directory for HTML templates.
- **Media:** For user-uploaded files.
- **Tests:** Tests for each app in a separate tests/ directory.
- **File Naming Conventions:**
- Use lowercase letters with underscores (snake_case) for Python files and variables (e.g., `models.py`, `user_profile`).
- Classes should use CamelCase (e.g., `UserProfile`).
- Function names should use snake_case (e.g., `get_user_profile`).
- **Module Organization:**
- Each app should be a self-contained module.
- Group related functionalities into submodules within the app.
- Use `__init__.py` files to define packages.
- **Component Architecture:**
- Follow the Model-View-Template (MVT) architecture.
- Keep models lean and focused on data representation.
- Use views for request handling and business logic.
- Templates should focus on presentation.
- **Code Splitting Strategies:**
- Break down large views into smaller, reusable functions or class-based views.
- Use mixins to share functionality across multiple views.
- Implement custom template tags and filters for reusable template logic.
- Consider using Celery for asynchronous task processing.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Model-View-Template (MVT):** Django's core architectural pattern.
- **Form Objects:** Use Django's forms for handling user input and validation.
- **Signals:** Implement signals for decoupled event handling.
- **Managers:** Use custom model managers to encapsulate query logic.
- **DRY (Don't Repeat Yourself):** Avoid redundant code by extracting reusable components.
- **Recommended Approaches:**
- **Database Interactions:** Use Django's ORM for database interactions. Avoid raw SQL queries unless necessary.
- **Form Handling:** Leverage Django's form classes for data validation and rendering forms.
- **URL Routing:** Use named URL patterns for reverse URL lookup.
- **Template Inheritance:** Utilize template inheritance to create a consistent look and feel.
- **Anti-patterns and Code Smells:**
- **Fat Models:** Avoid putting too much business logic in models. Use services or utility functions instead.
- **Complex Templates:** Keep templates simple and focused on presentation. Move complex logic to views or custom template tags.
- **Hardcoded Values:** Avoid hardcoding values in code. Use settings or environment variables.
- **Ignoring Security:** Neglecting security best practices can lead to vulnerabilities.
- **State Management:**
- Use Django's session framework for managing user sessions.
- Avoid storing sensitive data in sessions.
- Consider using a dedicated caching system (e.g., Redis, Memcached) for storing frequently accessed data.
- **Error Handling:**
- Implement proper error handling using `try...except` blocks.
- Use Django's logging framework to log errors and warnings.
- Display user-friendly error messages.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Database Optimization:** Use indexes on frequently queried fields.
- **Caching:** Implement caching at various levels (e.g., template caching, view caching, database caching).
- **Query Optimization:** Use `select_related` and `prefetch_related` to reduce the number of database queries.
- **Gzip Compression:** Enable Gzip compression for static files and responses.
- **Memory Management:**
- Avoid loading large datasets into memory. Use iterators or generators.
- Close database connections and file handles properly.
- Be mindful of memory leaks.
- **Rendering Optimization:**
- Minimize the use of complex template logic.
- Use template caching to cache rendered templates.
- Optimize images and other static assets.
- **Lazy Loading Strategies:**
- Implement lazy loading for images and other resources that are not immediately visible.
- Use pagination to display large datasets in smaller chunks.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates and using Django's `escape` filter.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Django's CSRF protection.
- **SQL Injection:** Use Django's ORM to prevent SQL injection attacks. Avoid raw SQL queries.
- **Authentication and Authorization Issues:** Implement proper authentication and authorization mechanisms.
- **Input Validation:**
- Validate all user input on both the client-side and server-side.
- Use Django's form validation to validate data.
- Sanitize user input to remove potentially harmful characters.
- **Authentication and Authorization:**
- Use Django's built-in authentication system for user authentication.
- Implement proper authorization checks to restrict access to sensitive resources.
- Use Django's permission system to manage user permissions.
- **Data Protection:**
- Store sensitive data securely using encryption.
- Use HTTPS to encrypt communication between the client and server.
- Protect against data breaches by implementing proper access controls and monitoring.
- **Secure API Communication:**
- Use authentication tokens or API keys to authenticate API requests.
- Implement rate limiting to prevent abuse.
- Validate all API input.
## 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual functions and classes.
- Use Django's testing framework to write and run tests.
- Mock external dependencies to isolate units of code.
- **Integration Testing:**
- Write integration tests to test the interaction between different components.
- Test database interactions, form handling, and view rendering.
- **End-to-End Testing:**
- Write end-to-end tests to test the entire application flow.
- Use tools like Selenium or Cypress to automate browser testing.
- **Test Organization:**
- Organize tests into separate test suites for each app or component.
- Use meaningful test names to describe what each test does.
- Keep tests concise and focused.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate units of code during testing.
- Avoid mocking external dependencies unless necessary.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Incorrect Database Configuration:** Ensure that the database settings are configured correctly.
- **Improper Static File Handling:** Configure static file serving properly in production.
- **Not Using Django's Built-in Features:** Leverage Django's built-in features instead of reinventing the wheel.
- **Ignoring Security Warnings:** Address any security warnings or vulnerabilities reported by Django's security checks.
- **Edge Cases:**
- **Handling Time Zones:** Be mindful of time zones and use Django's time zone support.
- **Dealing with Unicode:** Handle Unicode characters correctly.
- **Managing File Uploads:** Implement proper file upload handling to prevent security vulnerabilities.
- **Version-Specific Issues:**
- Be aware of compatibility issues between different Django versions.
- Consult the Django release notes for information about breaking changes.
- **Compatibility Concerns:**
- Ensure that your code is compatible with different browsers and devices.
- Test your application on different platforms.
- **Debugging Strategies:**
- Use Django's debugging tools to identify and fix errors.
- Use logging to track the execution flow of your application.
- Consult the Django documentation and community forums for help.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **IDE:** PyCharm, VS Code, Sublime Text
- **Package Manager:** pip, uv
- **Database Client:** pgAdmin, MySQL Workbench
- **Build Configuration:**
- Use a `requirements.txt` file to manage dependencies.
- Use a virtual environment to isolate project dependencies.
- **Linting and Formatting:**
- Use Black to format code automatically.
- Use flake8 to lint code and identify potential errors.
- **Deployment Best Practices:**
- Use a production-ready web server (e.g., Gunicorn, uWSGI).
- Configure a reverse proxy (e.g., Nginx, Apache).
- Use a database server (e.g., PostgreSQL, MySQL).
- **CI/CD Integration:**
- Integrate your project with a CI/CD pipeline to automate testing and deployment.
- Use tools like Jenkins, Travis CI, or GitLab CI.
## Additional Notes
- Always follow PEP 8 guidelines for Python code.
- Write clear and concise comments.
- Keep your code DRY (Don't Repeat Yourself).
- Regularly update your dependencies.
- Monitor your application for performance and security issues.
@@ -0,0 +1,336 @@
---
description: Comprehensive guidelines for developing robust, scalable, and maintainable FastAPI applications. Covers code structure, performance, security, testing, and common pitfalls.
globs: **/*.py
---
# FastAPI Best Practices: A Comprehensive Guide
This document provides a comprehensive set of best practices and coding standards for developing FastAPI applications. These guidelines cover various aspects of development, including project structure, common patterns, performance considerations, security, testing, and tooling.
## 1. Code Organization and Structure
A well-structured codebase is crucial for maintainability, scalability, and collaboration. Adopting a consistent and predictable project structure makes it easier for developers to navigate and understand the application.
### 1.1 Directory Structure Best Practices
Inspired by projects like Netflix's Dispatch, a feature-based directory structure is recommended, especially for larger applications:
fastapi-project/
├── alembic/ # Database migrations
├── src/ # Source code
│ ├── auth/ # Authentication module
│ │ ├── router.py # API endpoints for authentication
│ │ ├── schemas.py # Pydantic models for request/response
│ │ ├── models.py # Database models
│ │ ├── dependencies.py# Dependency injection definitions
│ │ ├── config.py # Local configurations
│ │ ├── constants.py # Constants and error codes
│ │ ├── exceptions.py # Custom exceptions
│ │ ├── service.py # Business logic
│ │ └── utils.py # Utility functions
│ ├── aws/ # AWS integration module (example)
│ │ ├── ...
│ ├── posts/ # Posts module
│ │ ├── ...
│ ├── config.py # Global configurations
│ ├── models.py # Global models
│ ├── exceptions.py # Global exceptions
│ ├── pagination.py # Pagination logic
│ ├── database.py # Database connection and ORM setup
│ └── main.py # Main application entry point
├── tests/ # Tests
│ ├── auth/
│ ├── aws/
│ └── posts/
├── templates/ # Jinja2 Templates
│ └── index.html
├── requirements/
│ ├── base.txt # Base dependencies
│ ├── dev.txt # Development dependencies
│ └── prod.txt # Production dependencies
├── .env # Environment variables
├── .gitignore # Git ignore file
├── logging.ini # Logging configuration
└── alembic.ini # Alembic configuration
Key aspects of this structure:
* `src/`: The root directory containing all application code.
* Module-based organization: Features are grouped into modules (e.g., `auth`, `posts`). Each module contains its own set of `router.py`, `schemas.py`, `models.py`, etc. This promotes loose coupling and high cohesion.
* `main.py`: The entry point of the FastAPI application.
* `config.py`: Stores global configurations.
* `database.py`: Handles database connection and ORM setup (e.g., SQLAlchemy).
* `requirements/`: Separate dependency files for different environments.
### 1.2 File Naming Conventions
* Python files: Use lowercase with underscores (e.g., `user_service.py`).
* Pydantic schemas: Use PascalCase with the suffix "Schema" or "Model" (e.g., `UserSchema`, `PostModel`).
* Database models: Use PascalCase (e.g., `User`, `Post`).
* Routers: Typically named `router.py` within each module.
* Configuration files: `config.py`
* Tests: `test_<module_name>.py` or `test_<feature>.py`
### 1.3 Module Organization
* **Routers**: Contain API endpoint definitions.
* **Schemas**: Define data structures using Pydantic models for request and response validation and serialization.
* **Models**: Represent database entities (if using an ORM).
* **Services**: Implement business logic, interacting with the database or other services.
* **Dependencies**: Define dependency injection functions used in route handlers.
* **Constants**: Store module-specific constants and error codes.
* **Configuration**: Store module-specific environment variables and settings.
* **Exceptions**: Define custom exceptions for specific modules.
* **Utils**: Contains general-purpose utility functions.
### 1.4 Component Architecture
* **Layered Architecture:** Separate the application into distinct layers (e.g., presentation, business logic, data access). This improves maintainability and testability.
* **Loose Coupling:** Design components to be independent and minimize dependencies between them. This allows for easier modification and replacement of components.
* **High Cohesion:** Ensure that each component has a single, well-defined responsibility.
* **Dependency Injection:** Use FastAPI's built-in dependency injection system to manage dependencies between components. This promotes testability and reusability. Favor interface-based dependency injection for added flexibility.
### 1.5 Code Splitting Strategies
* **Feature-Based Splitting:** Divide the codebase into modules based on application features (e.g., user management, product catalog, order processing). This makes it easier to understand and maintain the code.
* **Vertical Slicing:** Group related components (e.g., routers, schemas, models, services) into slices that represent specific use cases or functionalities.
* **Horizontal Splitting:** Separate components based on technical layers (e.g., presentation, business logic, data access). This is useful for enforcing separation of concerns but can lead to more complex dependencies if not managed carefully.
## 2. Common Patterns and Anti-patterns
Employ established design patterns and avoid common anti-patterns to write clean, efficient, and maintainable FastAPI code.
### 2.1 Design Patterns Specific to FastAPI
* **Repository Pattern:** Abstract data access logic behind a repository interface. This allows you to switch data sources easily (e.g., from a database to a mock for testing) and centralizes data access concerns.
* **Service Layer Pattern:** Encapsulate business logic in service classes. Routers then call the service layer. Promotes testability and keeps routes thin and focused on request/response handling.
* **Dependency Injection:** Utilize FastAPI's dependency injection system extensively for request validation, authentication, authorization, and accessing shared resources like database connections.
* **Asynchronous Operations:** Favor `async` functions for I/O-bound tasks to improve performance and concurrency.
* **Pydantic Models for Validation:** Use Pydantic models for request and response data validation. Enforce data types, constraints, and custom validation logic.
### 2.2 Recommended Approaches for Common Tasks
* **Configuration Management:** Use Pydantic's `BaseSettings` to manage environment variables and application settings.
* **Database Interactions:** Use an ORM like SQLAlchemy for interacting with databases. Define database models and use them for data access.
* **Authentication and Authorization:** Implement authentication and authorization using strategies like JWT (JSON Web Tokens) or OAuth 2.0. Use FastAPI's security utilities.
* **Error Handling:** Use `HTTPException` for returning meaningful error responses to the client. Define custom exception classes for specific error conditions.
* **Logging:** Configure logging using Python's `logging` module. Log important events and errors for debugging and monitoring.
### 2.3 Anti-patterns and Code Smells to Avoid
* **Fat Route Handlers:** Avoid putting too much logic directly inside route handlers. Delegate complex tasks to service classes or utility functions.
* **Tight Coupling:** Minimize dependencies between components to improve maintainability and testability.
* **Ignoring Asynchronous Operations:** Blocking I/O in async routes can negate the benefits of concurrency. Ensure all I/O operations in async routes are non-blocking.
* **Lack of Data Validation:** Failing to validate input data can lead to security vulnerabilities and unexpected behavior. Always use Pydantic models for data validation.
* **Hardcoding Values:** Avoid hardcoding values in the code. Use configuration files or environment variables instead.
* **Returning Pydantic objects directly from routes.** FastAPI makes an extra conversion. Return a dict.
### 2.4 State Management Best Practices
* **Stateless Applications:** FastAPI applications are typically stateless, meaning they don't store any persistent data within the application itself. This makes them easier to scale and deploy.
* **External Data Stores:** Store application state in external data stores like databases, caches, or message queues.
* **Dependency Injection for State:** Use dependency injection to provide access to shared resources or stateful objects to route handlers.
### 2.5 Error Handling Patterns
* **Centralized Exception Handling:** Implement a global exception handler to catch unhandled exceptions and return appropriate error responses.
* **Custom Exception Classes:** Define custom exception classes for specific error conditions. This makes it easier to identify and handle different types of errors.
* **Logging Errors:** Log all errors for debugging and monitoring.
* **Meaningful Error Messages:** Return meaningful error messages to the client to help them understand what went wrong.
## 3. Performance Considerations
FastAPI is known for its performance, but optimizations are still crucial for high-load applications.
### 3.1 Optimization Techniques
* **Asynchronous Operations:** Utilize `async` and `await` for I/O-bound operations to prevent blocking the event loop.
* **Database Connection Pooling:** Use a database connection pool to reuse database connections and reduce connection overhead.
* **Caching:** Implement caching for frequently accessed data to reduce database load and improve response times. Use tools like Redis or Memcached.
* **Gzip Compression:** Enable gzip compression for API responses to reduce the size of the data transmitted over the network.
* **Load Balancing:** Distribute traffic across multiple instances of the application to improve scalability and availability.
* **Profiling:** Use profiling tools to identify performance bottlenecks in the code.
### 3.2 Memory Management
* **Resource Management:** Properly manage resources like database connections, file handles, and network sockets. Close resources when they are no longer needed.
* **Data Structures:** Use efficient data structures like sets and dictionaries for fast lookups.
* **Generators:** Use generators for processing large datasets to avoid loading the entire dataset into memory at once.
* **Object Reuse:** Reuse objects whenever possible to reduce memory allocation overhead. Consider using object pools for frequently used objects.
### 3.3 Rendering Optimization
* **Template Caching:** Enable template caching for Jinja2 templates to reduce rendering overhead.
* **Minimize Template Logic:** Keep template logic simple and avoid complex computations in templates.
* **Content Delivery Network (CDN):** Use a CDN to serve static assets like images, CSS, and JavaScript files.
### 3.4 Bundle Size Optimization (for Frontend Integration)
* **Code Splitting:** Split the frontend code into smaller bundles that can be loaded on demand.
* **Tree Shaking:** Remove unused code from the frontend bundles using tree shaking techniques.
* **Minification:** Minify the frontend code to reduce its size.
* **Image Optimization:** Optimize images for the web by compressing them and using appropriate image formats.
### 3.5 Lazy Loading Strategies
* **Lazy Loading of Modules:** Use lazy loading to load modules only when they are needed.
* **Lazy Loading of Data:** Load data on demand instead of loading it all at once.
* **Asynchronous Loading:** Use asynchronous loading to load data in the background without blocking the main thread.
## 4. Security Best Practices
Security is paramount. Protect your FastAPI application from common web vulnerabilities.
### 4.1 Common Vulnerabilities and How to Prevent Them
* **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM with proper escaping.
* **Cross-Site Scripting (XSS):** Prevent XSS by sanitizing user input and escaping output data.
* **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens.
* **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms to protect sensitive data and resources.
* **Insecure Direct Object References (IDOR):** Prevent IDOR by verifying that users have access to the objects they are requesting.
* **Denial of Service (DoS):** Prevent DoS attacks by implementing rate limiting and input validation.
### 4.2 Input Validation
* **Pydantic Models:** Use Pydantic models to define data types, constraints, and validation rules for request bodies and query parameters.
* **Custom Validation Logic:** Implement custom validation logic for complex validation scenarios.
* **Sanitization:** Sanitize user input to remove potentially harmful characters or code.
### 4.3 Authentication and Authorization Patterns
* **JWT (JSON Web Tokens):** Use JWT for stateless authentication. Generate a JWT when a user logs in and verify the JWT on subsequent requests.
* **OAuth 2.0:** Use OAuth 2.0 for delegated authorization. Allow users to grant third-party applications access to their data without sharing their credentials.
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
* **Attribute-Based Access Control (ABAC):** Implement ABAC to control access to resources based on user attributes and resource attributes.
* **CORS (Cross-Origin Resource Sharing):** Configure CORS middleware properly to allow requests only from trusted origins.
### 4.4 Data Protection Strategies
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Hashing:** Hash passwords and other sensitive data using a strong hashing algorithm like bcrypt or Argon2.
* **Data Masking:** Mask sensitive data in logs and other output.
* **Data Anonymization:** Anonymize data to protect user privacy.
### 4.5 Secure API Communication
* **HTTPS:** Always use HTTPS to encrypt communication between the client and the server.
* **TLS/SSL Certificates:** Use valid TLS/SSL certificates to establish secure connections.
* **Strict Transport Security (HSTS):** Enable HSTS to force browsers to use HTTPS for all requests to the application.
* **Content Security Policy (CSP):** Configure CSP to prevent XSS attacks by controlling the sources from which the browser is allowed to load resources.
## 5. Testing Approaches
Write comprehensive tests to ensure the quality and reliability of your FastAPI application.
### 5.1 Unit Testing Strategies
* **Test Individual Components:** Write unit tests to test individual components like functions, classes, and modules in isolation.
* **Mock Dependencies:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to mock external dependencies and isolate the component being tested.
* **Test Edge Cases:** Test edge cases and boundary conditions to ensure that the component handles unexpected input correctly.
### 5.2 Integration Testing
* **Test Interactions Between Components:** Write integration tests to test the interactions between different components of the application.
* **Use a Test Database:** Use a separate test database for integration tests to avoid affecting the production database.
* **Test API Endpoints:** Write integration tests to test the API endpoints of the application.
### 5.3 End-to-End Testing
* **Test the Entire Application Flow:** Write end-to-end tests to test the entire application flow, from the client to the database.
* **Use a Testing Framework:** Use a testing framework like Selenium or Cypress to automate end-to-end tests.
* **Test User Interface (UI):** Test the user interface of the application to ensure that it is working correctly.
### 5.4 Test Organization
* **Organize Tests by Module:** Organize tests into separate directories or files based on the module or component being tested.
* **Use Descriptive Test Names:** Use descriptive test names that clearly indicate what the test is verifying.
* **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions.
* **Keep Tests Concise:** Keep tests concise and focused on a single aspect of the component being tested.
### 5.5 Mocking and Stubbing
* **Use Mocking Frameworks:** Use mocking frameworks like `unittest.mock` or `pytest-mock` to create mock objects and stub out external dependencies.
* **Mock External APIs:** Mock external APIs to isolate the component being tested and avoid making actual API calls during testing.
* **Stub Database Interactions:** Stub database interactions to avoid affecting the database during testing.
* **Verify Interactions:** Verify that the component being tested interacts with the mock objects as expected.
## 6. Common Pitfalls and Gotchas
Be aware of common pitfalls and gotchas that can arise when developing FastAPI applications.
### 6.1 Frequent Mistakes Developers Make
* **Incorrectly Using `Depends`:** Ensure `Depends` is used properly to inject dependencies into route handlers.
* **Blocking I/O in Async Routes:** Avoid blocking I/O operations in async routes.
* **Not Handling Exceptions:** Implement proper exception handling to prevent unhandled exceptions from crashing the application.
* **Ignoring Security Best Practices:** Follow security best practices to protect the application from vulnerabilities.
* **Not Writing Tests:** Write comprehensive tests to ensure the quality and reliability of the application.
### 6.2 Edge Cases to Be Aware Of
* **Unicode Handling:** Be aware of unicode handling issues when processing user input.
* **Time Zones:** Handle time zones correctly when working with dates and times.
* **Large File Uploads:** Handle large file uploads efficiently to prevent memory exhaustion.
* **Concurrency Issues:** Be aware of concurrency issues when working with shared resources in a multi-threaded or multi-process environment.
### 6.3 Version-Specific Issues
* **Check Changelogs:** Review the changelogs for FastAPI and its dependencies to be aware of any breaking changes or new features.
* **Test Compatibility:** Test the application with different versions of FastAPI and its dependencies to ensure compatibility.
### 6.4 Compatibility Concerns
* **Python Version:** Ensure that the application is compatible with the target Python version.
* **Operating System:** Test the application on different operating systems to ensure compatibility.
* **Database Compatibility:** Ensure that the application is compatible with the target database.
### 6.5 Debugging Strategies
* **Use a Debugger:** Use a debugger like `pdb` or `ipdb` to step through the code and inspect variables.
* **Logging:** Use logging to track the execution flow and identify errors.
* **Profiling:** Use profiling tools to identify performance bottlenecks.
* **Remote Debugging:** Use remote debugging to debug applications running on remote servers.
## 7. Tooling and Environment
Utilize the right tools and environment for efficient FastAPI development.
### 7.1 Recommended Development Tools
* **IDE:** VS Code, PyCharm, or other IDE with Python support.
* **Virtual Environment Manager:** `venv`, `conda`, or `poetry` for managing project dependencies.
* **Package Manager:** `pip` or `poetry` for installing and managing Python packages.
* **Debugger:** `pdb` or `ipdb` for debugging Python code.
* **Profiler:** `cProfile` or `py-spy` for profiling Python code.
### 7.2 Build Configuration
* **`requirements.txt`:** Use `requirements.txt` to specify project dependencies. Generate it using `pip freeze > requirements.txt`.
* **`pyproject.toml`:** Consider using `pyproject.toml` (with Poetry or similar tools) for more advanced dependency management and build configuration.
### 7.3 Linting and Formatting
* **Linters:** Use linters like `flake8`, `pylint`, or `ruff` to enforce code style and identify potential errors.
* **Formatters:** Use code formatters like `black` or `autopep8` to automatically format the code according to PEP 8 standards.
* **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
### 7.4 Deployment Best Practices
* **Containerization:** Use Docker to containerize the application for easy deployment and scaling.
* **Reverse Proxy:** Use a reverse proxy like Nginx or Apache to handle incoming requests and forward them to the application.
* **Process Manager:** Use a process manager like Supervisor or systemd to manage the application process.
* **Load Balancing:** Use a load balancer to distribute traffic across multiple instances of the application.
* **Monitoring:** Monitor the application using tools like Prometheus or Grafana.
### 7.5 CI/CD Integration
* **Continuous Integration (CI):** Set up a CI pipeline to automatically build, test, and lint the code on every commit.
* **Continuous Delivery (CD):** Set up a CD pipeline to automatically deploy the application to the production environment after the CI pipeline has passed.
* **Version Control:** Use a version control system like Git to manage the code and track changes.
* **Automated Testing:** Integrate automated tests into the CI/CD pipeline to ensure that the application is working correctly before deployment.
* **Automated Rollbacks:** Implement automated rollbacks to revert to a previous version of the application if a deployment fails.
## Conclusion
By adhering to these best practices, you can develop robust, scalable, and maintainable FastAPI applications that are secure, performant, and easy to test. This guide provides a foundation for building high-quality APIs with FastAPI.
@@ -0,0 +1,199 @@
---
description: This rule provides comprehensive best practices for developing Flask applications, covering code structure, security, performance, and testing.
globs: **/*.py
---
- ## Code Organization and Structure:
- **Directory Structure Best Practices:**
- Follow a modular and organized project structure. A common structure is:
project_root/
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── views.py # Or controllers.py
│ ├── forms.py
│ ├── utils.py # Helper functions
│ ├── api/
│ │ ├── __init__.py
│ │ ├── routes.py
│ ├── templates/
│ │ └── ...
│ ├── static/
│ │ └── ...
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Fixtures for tests
│ ├── test_models.py
│ ├── test_views.py
├── migrations/
│ └── ... # Alembic migrations
├── venv/ # Virtual environment
├── .env # Environment variables (use with caution, not for sensitive data in production)
├── config.py # Application configuration
├── requirements.txt or pyproject.toml # Dependencies
├── run.py # Application entry point
- Use Blueprints to organize routes and views into logical modules. Blueprints promote reusability and maintainability.
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Examples: `models.py`, `views.py`, `forms.py`, `utils.py`, `routes.py`, `test_*.py`.
- Maintain consistency throughout the project.
- **Module Organization:**
- Group related functionality into modules. For instance, database models in `models.py`, user authentication logic in `auth.py`, and utility functions in `utils.py`.
- Use `__init__.py` files to make directories packages, allowing you to import modules within the directory using relative paths.
- **Component Architecture:**
- Design components with clear responsibilities and interfaces.
- Consider using a layered architecture (e.g., presentation, business logic, data access) to separate concerns.
- Use dependency injection to decouple components.
- **Code Splitting Strategies:**
- Decompose large modules into smaller, more manageable files.
- Extract reusable code into separate modules or packages.
- Employ lazy loading for modules that are not immediately needed.
- ## Common Patterns and Anti-patterns:
- **Design Patterns Specific to Flask:**
- **Application Factory:** Use the application factory pattern to create Flask application instances. This allows for different configurations for different environments (development, testing, production).
python
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Initialize extensions (e.g., db, mail) here
db.init_app(app)
mail.init_app(app)
# Register blueprints
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
- **Blueprints:** Organize application functionality into reusable blueprints.
python
from flask import Blueprint
bp = Blueprint('my_blueprint', __name__, url_prefix='/my_blueprint')
@bp.route('/route')
def my_route():
return 'Hello from my_blueprint'
- **Recommended Approaches for Common Tasks:**
- **Database Interactions:** Use Flask-SQLAlchemy or another ORM for database interactions. Define models to represent database tables.
- **Form Handling:** Use Flask-WTF for form handling. This provides CSRF protection and simplifies form validation.
- **Authentication:** Use Flask-Login for user authentication. It provides utilities for managing user sessions and protecting routes.
- **API Development:** Use Flask-RESTful or Flask-API for building RESTful APIs. Consider using Marshmallow for serializing and deserializing data.
- **Anti-patterns and Code Smells to Avoid:**
- **Global State:** Avoid using global variables to store application state. Use the `g` object or session variables instead.
- **Tight Coupling:** Design components with loose coupling to improve maintainability and testability.
- **Fat Models/Views:** Keep models and views focused on their primary responsibilities. Move complex business logic to separate modules.
- **Hardcoding Configuration:** Avoid hardcoding configuration values. Use environment variables or a configuration file.
- **State Management Best Practices:**
- Use the Flask `session` object to store user-specific data across requests.
- For application-wide state, consider using a database or a caching mechanism.
- Avoid storing sensitive data in the session without proper encryption.
- **Error Handling Patterns:**
- Use `try...except` blocks to handle exceptions gracefully.
- Implement custom error handlers for specific exceptions. Return appropriate HTTP status codes and error messages.
- Use logging to record errors and warnings.
- Use Flask's `abort()` function to raise HTTP exceptions.
- ## Performance Considerations:
- **Optimization Techniques:**
- **Caching:** Implement caching to reduce database queries and improve response times. Use Flask-Caching or Redis.
- **Database Optimization:** Optimize database queries and use indexes to improve performance.
- **Profiling:** Use a profiler to identify performance bottlenecks in your code.
- **Memory Management:**
- Avoid memory leaks by properly closing database connections and releasing resources.
- Use generators to process large datasets efficiently.
- **Rendering Optimization:**
- Minimize the number of database queries in templates.
- Use template caching to reduce rendering time.
- **Bundle Size Optimization:**
- For larger front-end applications, use a bundler like Webpack or Parcel to optimize JavaScript and CSS files. Minify and compress assets.
- **Lazy Loading Strategies:**
- Implement lazy loading for images and other assets to improve initial page load time.
- Use code splitting to load only the necessary JavaScript code for each page.
- ## Security Best Practices:
- **Common Vulnerabilities and How to Prevent Them:**
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input in templates. Use Jinja2's autoescaping feature.
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using Flask-WTF, which provides CSRF protection.
- **Authentication and Authorization Issues:** Implement secure authentication and authorization mechanisms. Use strong passwords and protect user credentials.
- **Input Validation:**
- Validate all user input to prevent malicious data from entering your application.
- Use Flask-WTF for form validation.
- **Authentication and Authorization Patterns:**
- Use Flask-Login for user authentication.
- Implement role-based access control (RBAC) to restrict access to certain resources.
- Use JWT (JSON Web Tokens) for API authentication.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to secure communication between the client and the server.
- Store passwords securely using a strong hashing algorithm (e.g., bcrypt).
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Implement authentication and authorization for API endpoints.
- Validate API requests and responses.
- Use rate limiting to prevent abuse.
- ## Testing Approaches:
- **Unit Testing Strategies:**
- Write unit tests to verify the functionality of individual components.
- Use pytest or unittest for writing and running tests.
- Mock external dependencies to isolate components during testing.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the integration between the application and the database.
- **End-to-End Testing:**
- Write end-to-end tests to simulate user interactions with the application.
- Use Selenium or Cypress for end-to-end testing.
- **Test Organization:**
- Organize tests into separate directories based on functionality.
- Use descriptive test names.
- Follow the Arrange-Act-Assert pattern in your tests.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate components during testing.
- Use the `unittest.mock` module or a third-party mocking library like `mock`.
- ## Common Pitfalls and Gotchas:
- **Frequent Mistakes Developers Make:**
- **Not using a virtual environment:** Always use a virtual environment to isolate project dependencies.
- **Not handling exceptions properly:** Handle exceptions gracefully to prevent application crashes.
- **Exposing sensitive data:** Avoid exposing sensitive data in logs or error messages.
- **Edge Cases to Be Aware Of:**
- **Handling Unicode correctly:** Be aware of Unicode encoding issues when working with text data.
- **Dealing with time zones:** Use a consistent time zone throughout the application.
- **Version-Specific Issues:**
- Be aware of compatibility issues when upgrading Flask or its dependencies.
- Consult the Flask documentation for version-specific information.
- **Compatibility Concerns:**
- Ensure that your application is compatible with different browsers and operating systems.
- Test your application on different devices.
- **Debugging Strategies:**
- Use the Flask debugger to identify and fix errors.
- Use logging to record errors and warnings.
- Use a profiler to identify performance bottlenecks.
- ## Tooling and Environment:
- **Recommended Development Tools:**
- **Virtual Environment Manager:** `virtualenv`, `venv`, or `conda`
- **Package Manager:** `pip` or `pipenv` or `poetry`
- **IDE/Text Editor:** VS Code, PyCharm, Sublime Text
- **Debugger:** `pdb` or `ipdb`
- **Profiler:** `cProfile`
- **Build Configuration:**
- Use a `requirements.txt` or `pyproject.toml` file to specify project dependencies.
- Use a build system like `setuptools` or `poetry` to package your application.
- **Linting and Formatting:**
- Use a linter like `flake8` or `pylint` to enforce code style guidelines.
- Use a formatter like `black` or `autopep8` to automatically format your code.
- **Deployment Best Practices:**
- Use a production-ready WSGI server like Gunicorn or uWSGI.
- Use a reverse proxy like Nginx or Apache to serve static files and handle SSL termination.
- Deploy your application to a cloud platform like AWS, Google Cloud, or Azure.
- **CI/CD Integration:**
- Use a CI/CD pipeline to automate testing, building, and deployment.
- Use tools like Jenkins, Travis CI, or GitHub Actions.