mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+125
-196
@@ -1,223 +1,152 @@
|
||||
---
|
||||
description: This rule file outlines best practices and coding standards for developing Sanic applications, covering code organization, performance, security, testing, and common pitfalls.
|
||||
globs: *.py
|
||||
description: Definitive guidelines for building high-performance, maintainable, and secure Sanic applications using modern Python async best practices.
|
||||
globs: **/*.py
|
||||
---
|
||||
- This document outlines the best practices for developing applications using the Sanic framework. Following these guidelines will lead to more maintainable, performant, and secure applications.
|
||||
# sanic Best Practices
|
||||
|
||||
Sanic is built for speed and scalability. To harness its full power and maintain a robust codebase, adhere strictly to these guidelines.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Directory Structure:** Organize your project into logical directories. A recommended structure is:
|
||||
|
||||
project_root/
|
||||
├── app/
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py # Main application file
|
||||
│ ├── routes.py # Defines application routes
|
||||
│ ├── models.py # Data models (if using an ORM)
|
||||
│ ├── views.py # Request handlers and view logic
|
||||
│ ├── config.py # Application configuration
|
||||
│ ├── utils.py # Utility functions and helpers
|
||||
│ ├── middlewares.py # Sanic middlewares
|
||||
│ ├── exceptions.py # Custom exception definitions
|
||||
│ └── services/ # Business logic and service layers
|
||||
├── tests/ # Unit and integration tests
|
||||
│ ├── __init__.py
|
||||
│ ├── conftest.py # Pytest configuration file
|
||||
│ ├── unit/
|
||||
│ └── integration/
|
||||
├── migrations/ # Database migration scripts
|
||||
├── requirements.txt # Project dependencies
|
||||
├── .env # Environment variables
|
||||
└── README.md # Project documentation
|
||||
|
||||
Always structure your Sanic application using the **factory pattern** and **Blueprints** for modularity. Keep configuration separate.
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent naming.
|
||||
- `routes.py`, `models.py`, `views.py`, `config.py`, etc. are good examples.
|
||||
- For service modules, use `service_name_service.py` (e.g., `user_service.py`).
|
||||
- Test files should mirror the source file names (e.g., `test_routes.py` for `routes.py`).
|
||||
❌ BAD: Global app instance, monolithic file
|
||||
```python
|
||||
# app.py
|
||||
from sanic import Sanic, response
|
||||
|
||||
- **Module Organization:**
|
||||
- Keep modules focused and cohesive.
|
||||
- Avoid large, monolithic modules.
|
||||
- Group related functionality into separate modules and packages.
|
||||
- Use relative imports within the `app` package.
|
||||
app = Sanic("my_app") # Global instance is hard to test and configure
|
||||
|
||||
- **Component Architecture:**
|
||||
- Adopt a layered architecture (e.g., presentation, business logic, data access).
|
||||
- Use dependency injection to decouple components.
|
||||
- Employ service objects for complex business logic.
|
||||
@app.route("/")
|
||||
async def hello_world(request):
|
||||
return response.json({"message": "Hello!"})
|
||||
|
||||
- **Code Splitting:**
|
||||
- Defer loading non-critical modules using dynamic imports.
|
||||
- Split large route handlers into smaller, manageable functions.
|
||||
# Configuration directly in code
|
||||
app.config.DB_URL = "sqlite:///db.sqlite"
|
||||
```
|
||||
|
||||
✅ GOOD: Factory pattern, Blueprints, external config
|
||||
```python
|
||||
# config.py
|
||||
import os
|
||||
|
||||
class Config:
|
||||
DB_URL = os.getenv("DB_URL", "sqlite:///db.sqlite")
|
||||
SECRET_KEY = os.getenv("SECRET_KEY", "super-secret-key")
|
||||
|
||||
# app.py
|
||||
from sanic import Sanic
|
||||
from .config import Config
|
||||
from .blueprints.users import bp as users_bp
|
||||
from .blueprints.auth import bp as auth_bp
|
||||
|
||||
def create_app() -> Sanic:
|
||||
app = Sanic("my_app")
|
||||
app.config.update(Config.__dict__) # Load config from a dedicated object
|
||||
|
||||
app.blueprint(users_bp)
|
||||
app.blueprint(auth_bp)
|
||||
|
||||
# Add listeners, middleware, etc. here
|
||||
@app.listener("before_server_start")
|
||||
async def setup_db(app, loop):
|
||||
# Example: Initialize a database connection pool
|
||||
app.ctx.db = "AsyncDatabaseConnection" # Placeholder for actual DB setup
|
||||
print(f"Connecting to DB: {app.config.DB_URL}")
|
||||
|
||||
return app
|
||||
|
||||
# blueprints/users.py
|
||||
from sanic import Blueprint, Request, response
|
||||
from typing import Dict, Any
|
||||
|
||||
bp = Blueprint("users", url_prefix="/users")
|
||||
|
||||
@bp.route("/", methods=["GET"])
|
||||
async def get_all_users(request: Request) -> response.HTTPResponse:
|
||||
# Simulate async DB call using app.ctx.db
|
||||
# await request.app.ctx.db.fetch_all("SELECT * FROM users")
|
||||
return response.json([{"id": 1, "name": "Alice"}])
|
||||
|
||||
@bp.route("/<user_id:int>", methods=["GET"])
|
||||
async def get_user(request: Request, user_id: int) -> response.HTTPResponse:
|
||||
# Simulate async DB call
|
||||
# user = await request.app.ctx.db.fetch_one(f"SELECT * FROM users WHERE id={user_id}")
|
||||
user = {"id": user_id, "name": "Alice"} # Placeholder
|
||||
if user:
|
||||
return response.json(user)
|
||||
return response.json({"message": "User not found"}, status=404)
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Dependency Injection:** Use dependency injection to manage dependencies and improve testability.
|
||||
- **Service Layer:** Encapsulate business logic in service objects.
|
||||
- **Repository Pattern:** Abstract data access logic using repositories.
|
||||
- **Middleware Pattern:** Use middleware for request pre-processing and response post-processing.
|
||||
**Never block the event loop.** Sanic's performance hinges on non-blocking I/O. Offload heavy computations or blocking I/O to background tasks or external services.
|
||||
|
||||
- **Recommended Approaches:**
|
||||
- **Configuration:** Use environment variables for configuration and load them with a library like `python-dotenv`.
|
||||
- **Database Access:** Utilize an ORM (e.g., SQLAlchemy) for interacting with databases.
|
||||
- **Asynchronous Tasks:** Use `asyncio` or a task queue (e.g., Celery) for background tasks.
|
||||
- **Response Handling:** Standardize response formats and error handling using custom exception handlers.
|
||||
❌ BAD: Blocking I/O in a handler
|
||||
```python
|
||||
import time
|
||||
from sanic import Request, response
|
||||
|
||||
- **Anti-patterns:**
|
||||
- **Global State:** Avoid using global variables to store application state; use dependency injection instead.
|
||||
- **Tight Coupling:** Reduce coupling between components through interfaces and dependency injection.
|
||||
- **Long Functions:** Break down large functions into smaller, more manageable units.
|
||||
- **Ignoring Exceptions:** Always handle exceptions properly; avoid bare `except` clauses.
|
||||
@app.route("/blocking")
|
||||
async def blocking_endpoint(request: Request) -> response.HTTPResponse:
|
||||
time.sleep(5) # Blocks the entire event loop!
|
||||
return response.json({"message": "Done after 5s"})
|
||||
```
|
||||
|
||||
- **State Management:**
|
||||
- Use application context or dependency injection to manage shared state.
|
||||
- Avoid using global variables.
|
||||
- Utilize a dedicated state management library (if needed).
|
||||
✅ GOOD: Use `asyncio.sleep` or offload blocking work
|
||||
```python
|
||||
import asyncio
|
||||
from sanic import Request, response
|
||||
from concurrent.futures import ThreadPoolExecutor # For I/O-bound blocking tasks
|
||||
from typing import Dict, Any
|
||||
|
||||
- **Error Handling:**
|
||||
- Use custom exception classes for specific error conditions.
|
||||
- Implement global exception handlers for uncaught exceptions.
|
||||
- Log errors with detailed context information.
|
||||
- Return informative error messages to the client.
|
||||
# Use a global executor or pass it via app.ctx
|
||||
executor = ThreadPoolExecutor()
|
||||
|
||||
def heavy_blocking_io_task(data: int) -> Dict[str, int]:
|
||||
# Simulate I/O-bound blocking task
|
||||
time.sleep(2)
|
||||
return {"result": data * 2}
|
||||
|
||||
@app.route("/non_blocking")
|
||||
async def non_blocking_endpoint(request: Request) -> response.HTTPResponse:
|
||||
await asyncio.sleep(0.1) # Yields control, doesn't block
|
||||
return response.json({"message": "Done quickly"})
|
||||
|
||||
@app.route("/heavy_io_task")
|
||||
async def heavy_io_task_endpoint(request: Request) -> response.HTTPResponse:
|
||||
data = request.json.get("value", 10) if request.json else 10
|
||||
# Run blocking I/O in a thread pool
|
||||
result = await request.app.loop.run_in_executor(executor, heavy_blocking_io_task, data)
|
||||
return response.json(result)
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Asynchronous Operations:** Use `async` and `await` for I/O-bound operations to prevent blocking the event loop.
|
||||
- **Connection Pooling:** Use connection pooling for database connections to reduce overhead.
|
||||
- **Caching:** Implement caching strategies to reduce database load.
|
||||
- **Gzip Compression:** Enable Gzip compression for responses to reduce network bandwidth usage.
|
||||
Leverage Sanic's async nature. Use `app.add_task` for fire-and-forget background operations.
|
||||
|
||||
- **Memory Management:**
|
||||
- Avoid creating unnecessary objects.
|
||||
- Use generators for large datasets to reduce memory consumption.
|
||||
- Profile your application to identify memory leaks.
|
||||
✅ GOOD: Background tasks for non-critical work
|
||||
```python
|
||||
from sanic import Sanic, Request, response
|
||||
import asyncio
|
||||
|
||||
- **Rendering Optimization:**
|
||||
- Use efficient template engines (e.g., Jinja2) and cache rendered templates.
|
||||
- Minimize the amount of data passed to templates.
|
||||
- Use response streaming for very large responses.
|
||||
app = Sanic("perf_app")
|
||||
|
||||
- **Bundle Size Optimization:**
|
||||
- Not directly applicable to Sanic (as it's a backend framework), but if serving static files, minimize and compress them.
|
||||
async def send_email_async(recipient: str, subject: str, body: str):
|
||||
await asyncio.sleep(2) # Simulate I/O for sending email
|
||||
print(f"Email sent to {recipient}: {subject}")
|
||||
|
||||
- **Lazy Loading:**
|
||||
- Defer loading non-critical modules until they are needed.
|
||||
- Use lazy imports to improve startup time.
|
||||
@app.route("/signup", methods=["POST"])
|
||||
async def signup(request: Request) -> response.HTTPResponse:
|
||||
user_data = request.json
|
||||
# ... save user to DB ...
|
||||
|
||||
## 4. Security Best Practices
|
||||
# Add email sending to background task, doesn't block response
|
||||
request.app.add_task(send_email_async(user_data["email"], "Welcome!", "Thanks for signing up!"))
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **SQL Injection:** Prevent SQL injection by using parameterized queries or an ORM.
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection for state-changing requests.
|
||||
- **Authentication and Authorization Issues:** Secure your application with proper authentication and authorization mechanisms.
|
||||
return response.json({"message": "User signed up successfully"}, status=201)
|
||||
```
|
||||
|
||||
- **Input Validation:**
|
||||
- Validate all user input to prevent injection attacks.
|
||||
- Use data validation libraries (e.g., `marshmallow`) to enforce data types and constraints.
|
||||
- Escape special characters in user input.
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
- **Authentication and Authorization:**
|
||||
- Use a secure authentication protocol (e.g., OAuth 2.0, JWT).
|
||||
- Implement role-based access control (RBAC) to manage user permissions.
|
||||
- Protect sensitive endpoints with authentication and authorization middleware.
|
||||
|
||||
- **Data Protection:**
|
||||
- Use HTTPS to encrypt data in transit.
|
||||
- Store sensitive data (e.g., passwords) securely using hashing and salting.
|
||||
- Use encryption for data at rest.
|
||||
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API endpoints.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
- Validate API requests and responses against a schema.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- **Unit Testing:**
|
||||
- Use a testing framework like `pytest` or `unittest`.
|
||||
- Write unit tests for individual components (e.g., models, services, utilities).
|
||||
- Mock external dependencies to isolate components.
|
||||
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components.
|
||||
- Use a test database for integration tests.
|
||||
- Verify that requests are handled correctly and data is persisted.
|
||||
|
||||
- **End-to-End Testing:**
|
||||
- Use a tool like `Selenium` or `Playwright` to simulate user interactions.
|
||||
- Test the entire application flow from the client to the database.
|
||||
- Verify that the application behaves as expected in a production-like environment.
|
||||
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories (e.g., `unit`, `integration`).
|
||||
- Use descriptive test names.
|
||||
- Follow the arrange-act-assert pattern.
|
||||
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to isolate components.
|
||||
- Create stubs for external dependencies that are difficult to test directly.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- **Frequent Mistakes:**
|
||||
- **Blocking the Event Loop:** Avoid performing long-running or I/O-bound operations in the main event loop.
|
||||
- **Incorrect Use of `async` and `await`:** Ensure that all asynchronous operations are properly awaited.
|
||||
- **Not Handling Exceptions:** Always handle exceptions properly to prevent application crashes.
|
||||
- **Security Vulnerabilities:** Be aware of common security vulnerabilities and take steps to prevent them.
|
||||
|
||||
- **Edge Cases:**
|
||||
- **Handling Large Requests:** Properly handle large requests to prevent denial-of-service attacks.
|
||||
- **Graceful Shutdown:** Implement graceful shutdown to avoid data loss.
|
||||
- **Concurrency Issues:** Be aware of potential concurrency issues when working with shared resources.
|
||||
|
||||
- **Version-Specific Issues:**
|
||||
- Consult the Sanic documentation and release notes for version-specific issues and migration guides.
|
||||
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your dependencies are compatible with the version of Sanic you are using.
|
||||
- Test your application with different versions of Python to ensure compatibility.
|
||||
|
||||
- **Debugging Strategies:**
|
||||
- Use the built-in debugger or an IDE with debugging support.
|
||||
- Log detailed information about requests and responses.
|
||||
- Use profiling tools to identify performance bottlenecks.
|
||||
- Check Sanic application and server logs when troubleshooting issues.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **IDE:** VS Code, PyCharm
|
||||
- **Package Manager:** pip, uv
|
||||
- **Virtual Environment:** venv, virtualenv
|
||||
- **Testing Framework:** pytest
|
||||
- **Linting:** flake8, pylint
|
||||
- **Formatting:** black, autopep8
|
||||
- **Debugging:** pdb, ipdb
|
||||
|
||||
- **Build Configuration:**
|
||||
- Use a `requirements.txt` file to manage dependencies.
|
||||
- Use a `Makefile` or `tox.ini` file to automate build tasks.
|
||||
- Use a `Dockerfile` to containerize your application.
|
||||
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter (e.g., `flake8`, `pylint`) to enforce code style.
|
||||
- Use a formatter (e.g., `black`, `autopep8`) to automatically format your code.
|
||||
- Configure your IDE to run linters and formatters automatically.
|
||||
|
||||
- **Deployment Best Practices:**
|
||||
- Use a process manager like `Gunicorn` or `uvicorn` to serve your application.
|
||||
- Deploy your application behind a reverse proxy like `Nginx`.
|
||||
- Use a containerization platform like `Docker` to package and deploy your application.
|
||||
- Monitor your application using a monitoring tool like `Prometheus` or `Sentry`.
|
||||
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like `GitHub Actions`, `GitLab CI`, or `Jenkins` to automate the build, test, and deployment process.
|
||||
- Configure your CI/CD pipeline to run linters, formatters, and tests.
|
||||
- Use a deployment strategy like blue-green deployment or canary deployment.
|
||||
|
||||
By adhering to these best practices, you can develop robust, scalable, and maintainable applications using the Sanic framework. Remember to stay updated with the latest Sanic documentation and community recommendations.
|
||||
Forgetting `await` is a common mistake that leads to unhandled coroutines and unexpected behavior. Always `await` coroutine calls.
|
||||
Reference in New Issue
Block a user