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:
+290
-167
@@ -1,176 +1,299 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing secure, maintainable, and performant applications using the Pyramid web framework for Python. It covers code structure, security, testing, and deployment considerations.
|
||||
globs: *.py
|
||||
description: This guide provides opinionated, actionable best practices for building modern, maintainable, and performant applications with the Pyramid web framework.
|
||||
globs: **/*.py
|
||||
---
|
||||
- **Project Structure and Code Organization:**
|
||||
- **Directory Structure:**
|
||||
- `src/`: Contains the main application code.
|
||||
- `src/<project_name>/`: Main application package.
|
||||
- `__init__.py`: Makes the directory a Python package.
|
||||
- `models.py`: Data models (if using an ORM like SQLAlchemy).
|
||||
- `views.py`: View callables (controllers).
|
||||
- `routes.py`: Route configurations.
|
||||
- `templates/`: Jinja2 or other template files.
|
||||
- `static/`: Static assets (CSS, JavaScript, images).
|
||||
- `scripts/`: Management scripts (e.g., database setup, data migration).
|
||||
- `tests/`: Unit and integration tests.
|
||||
- `__init__.py`: Makes the directory a Python package.
|
||||
- `conftest.py`: pytest configuration file.
|
||||
- `test_*.py`: Test modules.
|
||||
- `docs/`: Project documentation (Sphinx).
|
||||
- `venv/`: Virtual environment (should be excluded from version control).
|
||||
- **File Naming Conventions:**
|
||||
- Python files: `snake_case.py` (e.g., `database_utils.py`).
|
||||
- Class names: `CamelCase` (e.g., `User`).
|
||||
- Variable names: `snake_case` (e.g., `user_id`).
|
||||
- Constants: `UPPER_SNAKE_CASE` (e.g., `DEFAULT_TIMEOUT`).
|
||||
- **Module Organization:**
|
||||
- Group related functionality into modules.
|
||||
- Avoid circular dependencies.
|
||||
- Use relative imports within the application package (e.g., `from .models import User`).
|
||||
- **Component Architecture:**
|
||||
- MVC (Model-View-Controller) is a common pattern in Pyramid.
|
||||
- Models represent data and business logic.
|
||||
- Views handle requests and render responses.
|
||||
- Controllers (view callables) act as intermediaries between models and views.
|
||||
- **Code Splitting:**
|
||||
- Break down large modules into smaller, more manageable files.
|
||||
- Use packages to group related modules.
|
||||
- Consider using a service layer to separate business logic from view callables.
|
||||
# pyramid Best Practices
|
||||
|
||||
- **Common Patterns and Anti-Patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Service Layer Pattern:** Encapsulate business logic in a separate layer.
|
||||
- **Factory Pattern:** Use factories to create complex objects.
|
||||
- **Recommended Approaches:**
|
||||
- Use URL dispatch for routing requests to view callables.
|
||||
- Use decorators (`@view_config`) to associate views with routes.
|
||||
- Use Jinja2 or another templating engine for rendering dynamic content.
|
||||
- Use SQLAlchemy or another ORM for interacting with databases.
|
||||
- **Anti-Patterns:**
|
||||
- **Fat Views:** Avoid putting too much logic in view callables.
|
||||
- **Tight Coupling:** Design components to be loosely coupled.
|
||||
- **Ignoring Exceptions:** Always handle exceptions appropriately.
|
||||
- **State Management:**
|
||||
- Use request attributes to store request-specific data (e.g., database connection, user session).
|
||||
- Use sessions to store user-specific data across multiple requests.
|
||||
- Avoid storing large amounts of data in sessions.
|
||||
- **Error Handling:**
|
||||
- Use try-except blocks to handle exceptions.
|
||||
- Log exceptions with appropriate severity levels (e.g., `error`, `warning`, `info`).
|
||||
- Provide user-friendly error messages.
|
||||
- Use Pyramid's exception views to handle exceptions globally.
|
||||
Pyramid is a flexible, "pay-only-what-you-use" Python web framework. To build robust and scalable Pyramid applications, adhere to these modern best practices.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use caching to store frequently accessed data (e.g., using `dogpile.cache`).
|
||||
- Optimize database queries (e.g., using indexes, avoiding N+1 queries).
|
||||
- Minimize the number of database connections.
|
||||
- Use efficient data structures and algorithms.
|
||||
- **Memory Management:**
|
||||
- Avoid creating unnecessary objects.
|
||||
- Use generators and iterators to process large datasets.
|
||||
- Clean up resources properly (e.g., closing database connections).
|
||||
- **Rendering Optimization:**
|
||||
- Use template caching.
|
||||
- Minimize the amount of data passed to templates.
|
||||
- Optimize template code.
|
||||
- **Bundle Size Optimization:** (If serving static assets)
|
||||
- Minify CSS and JavaScript files.
|
||||
- Use a content delivery network (CDN) to serve static assets.
|
||||
- **Lazy Loading:**
|
||||
- Lazy-load images and other resources.
|
||||
- Defer loading of non-essential JavaScript.
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- **SQL Injection:** Prevent by using parameterized queries or an ORM that escapes input.
|
||||
- **Cross-Site Scripting (XSS):** Prevent by escaping output in templates.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use Pyramid's CSRF protection features.
|
||||
- **Authentication and Authorization Issues:** Implement strong authentication and authorization mechanisms.
|
||||
- **Session Hijacking:** Use secure cookies and regenerate session IDs after login.
|
||||
- **Input Validation:**
|
||||
- Validate all user input.
|
||||
- Use schema validation libraries (e.g., `colander`) to validate input data.
|
||||
- Sanitize input to remove potentially malicious characters.
|
||||
- **Authentication and Authorization:**
|
||||
- Use a robust authentication system (e.g., `pyramid_jwt`, `pyramid_authsanity`).
|
||||
- Implement role-based access control (RBAC).
|
||||
- Secure API endpoints with authentication and authorization checks.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use TLS/SSL for secure communication.
|
||||
- Store passwords securely using strong hashing algorithms (e.g., bcrypt, argon2).
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API requests.
|
||||
- Authenticate API clients using API keys or tokens.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
Organize your application for clarity, testability, and scalability. Avoid monolithic `__init__.py` files.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Test individual components in isolation.
|
||||
- Use mocking to isolate components from dependencies.
|
||||
- Use a testing framework (e.g., `pytest`).
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between multiple components.
|
||||
- Test the application's integration with external systems (e.g., databases).
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application from the user's perspective.
|
||||
- Use a browser automation tool (e.g., `Selenium`, `Playwright`).
|
||||
- **Test Organization:**
|
||||
- Keep tests in a separate `tests/` directory.
|
||||
- Organize tests into modules that correspond to the application's modules.
|
||||
- Use clear and descriptive test names.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to create mock objects.
|
||||
- Use stubs to replace dependencies with simplified versions.
|
||||
### 1.1. Enforce Code Style with `black` and `flake8`
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- **Misunderstanding URL Dispatch:** Carefully define routes and view predicates.
|
||||
- **Insecure Configuration:** Protect sensitive configuration data.
|
||||
- **Insufficient Testing:** Thoroughly test all parts of the application.
|
||||
- **Edge Cases:**
|
||||
- **Handling Unicode:** Ensure proper Unicode handling throughout the application.
|
||||
- **Dealing with Time Zones:** Use a consistent time zone and handle time zone conversions correctly.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of compatibility issues when upgrading Pyramid or its dependencies.
|
||||
- Consult the release notes for any breaking changes.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility between Pyramid and other technologies used in the application.
|
||||
- Test the application on all supported platforms and browsers.
|
||||
- **Debugging Strategies:**
|
||||
- Use a debugger to step through code and inspect variables.
|
||||
- Use logging to track the flow of execution and identify errors.
|
||||
- Use Pyramid's debugging toolbar to inspect requests, responses, and configuration.
|
||||
Always format your code automatically and lint it. Integrate `black` and `flake8` with `pre-commit` hooks.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Tools:**
|
||||
- **Virtualenv or venv:** For creating isolated Python environments.
|
||||
- **pip:** For managing dependencies.
|
||||
- **pytest:** For running tests.
|
||||
- **flake8:** For linting code.
|
||||
- **black:** For formatting code.
|
||||
- **Build Configuration:**
|
||||
- Use a `setup.py` or `pyproject.toml` file to define the project's metadata and dependencies.
|
||||
- Use a build system (e.g., `setuptools`, `poetry`) to package the application.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter (e.g., `flake8`) to enforce code style guidelines.
|
||||
- Use a formatter (e.g., `black`) to automatically format code.
|
||||
- Configure the linter and formatter to use consistent settings.
|
||||
- **Deployment:**
|
||||
- Use a WSGI server (e.g., `gunicorn`, `uWSGI`) to serve the application.
|
||||
- Use a process manager (e.g., `systemd`, `supervisor`) to manage the WSGI server.
|
||||
- Deploy the application to a production environment (e.g., cloud platform, virtual machine).
|
||||
- **CI/CD:**
|
||||
- Use a continuous integration/continuous deployment (CI/CD) system (e.g., `Jenkins`, `GitLab CI`, `GitHub Actions`) to automate the build, test, and deployment process.
|
||||
- Run tests automatically on every commit.
|
||||
- Deploy the application automatically to staging and production environments.
|
||||
**❌ BAD - Inconsistent Formatting & Linting**
|
||||
```python
|
||||
# Inconsistent spacing, line length, and missing imports
|
||||
from pyramid.view import view_config
|
||||
import os
|
||||
def my_view(request):
|
||||
data = request.json_body
|
||||
if data and 'name' in data:
|
||||
return {'status': 'ok', 'message': f"Hello, {data['name']}!"}
|
||||
return {'status': 'error', 'message': 'Name is required.'}
|
||||
```
|
||||
|
||||
- **Additional Information:**
|
||||
- Regularly update dependencies to patch security vulnerabilities.
|
||||
- Use a security scanner like Bandit to identify potential security flaws in the code.
|
||||
- Follow the principle of least privilege when granting permissions to users and services.
|
||||
- Monitor the application's performance and security logs to detect and respond to incidents.
|
||||
- Document the application's architecture, configuration, and deployment process.
|
||||
**✅ GOOD - Automated Formatting & Linting**
|
||||
```python
|
||||
# Ensure your pre-commit setup handles this automatically
|
||||
# Example .pre-commit-config.yaml:
|
||||
# - repo: https://github.com/psf/black
|
||||
# rev: 23.1.0
|
||||
# hooks: [- id: black]
|
||||
# - repo: https://github.com/PyCQA/flake8
|
||||
# rev: 6.0.0
|
||||
# hooks: [- id: flake8]
|
||||
|
||||
from pyramid.view import view_config
|
||||
from pyramid.response import Response
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="hello", renderer="json")
|
||||
def my_view(request) -> Dict[str, str]:
|
||||
"""Handles a greeting request."""
|
||||
data: Dict[str, Any] = request.json_body
|
||||
if data and "name" in data:
|
||||
return {"status": "ok", "message": f"Hello, {data['name']}!"}
|
||||
return Response(json_body={"status": "error", "message": "Name is required."}, status=400)
|
||||
```
|
||||
|
||||
### 1.2. Modularize Configuration
|
||||
|
||||
Separate your application's configuration (routes, views, security) into distinct modules. Use `config.include()` to compose your application.
|
||||
|
||||
**❌ BAD - Monolithic `__init__.py`**
|
||||
```python
|
||||
# myapp/__init__.py
|
||||
from pyramid.config import Configurator
|
||||
from pyramid.view import view_config
|
||||
|
||||
def main(global_config, **settings):
|
||||
with Configurator(settings=settings) as config:
|
||||
config.add_route('home', '/')
|
||||
config.add_route('users', '/users')
|
||||
config.add_route('user_detail', '/users/{id}')
|
||||
|
||||
@view_config(route_name='home', renderer='json')
|
||||
def home_view(request):
|
||||
return {'project': 'myapp'}
|
||||
|
||||
# ... hundreds of lines of routes and views ...
|
||||
return config.make_wsgi_app()
|
||||
```
|
||||
|
||||
**✅ GOOD - Modular Configuration with `include()`**
|
||||
```python
|
||||
# myapp/__init__.py
|
||||
from pyramid.config import Configurator
|
||||
|
||||
def main(global_config, **settings):
|
||||
with Configurator(settings=settings) as config:
|
||||
config.include("pyramid_jinja2") # Example external package
|
||||
config.include(".routes") # Local routes
|
||||
config.include(".views") # Local views (for decorator-based views)
|
||||
config.include(".security") # Local security policies
|
||||
config.scan(".") # Scan for decorator-based views and subscribers
|
||||
return config.make_wsgi_app()
|
||||
|
||||
# myapp/routes.py
|
||||
def includeme(config):
|
||||
config.add_route("home", "/")
|
||||
config.add_route("users", "/users")
|
||||
config.add_route("user_detail", "/users/{id}")
|
||||
|
||||
# myapp/views.py (or specific modules like myapp/views/user.py)
|
||||
from pyramid.view import view_config
|
||||
from pyramid.response import Response
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="home", renderer="json")
|
||||
def home_view(request) -> Dict[str, str]:
|
||||
return {"project": "myapp"}
|
||||
|
||||
@view_config(route_name="users", request_method="GET", renderer="json")
|
||||
def list_users_view(request) -> Dict[str, Any]:
|
||||
# ... logic to list users ...
|
||||
return {"users": []}
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
Leverage Pyramid's design principles to write clean, maintainable code.
|
||||
|
||||
### 2.1. Use View Predicates for Conditional Logic
|
||||
|
||||
Avoid `if/else` statements within views to handle different request methods, authentication states, or other request properties. Use `@view_config` predicates instead.
|
||||
|
||||
**❌ BAD - Logic in View**
|
||||
```python
|
||||
from pyramid.view import view_config
|
||||
from pyramid.response import Response
|
||||
|
||||
@view_config(route_name="items", renderer="json")
|
||||
def items_view(request):
|
||||
if request.method == "GET":
|
||||
return {"items": ["item1", "item2"]}
|
||||
elif request.method == "POST":
|
||||
# ... create item logic ...
|
||||
return Response(json_body={"message": "Item created"}, status=201)
|
||||
else:
|
||||
return Response(status=405) # Method Not Allowed
|
||||
```
|
||||
|
||||
**✅ GOOD - Predicates for Clarity**
|
||||
```python
|
||||
from pyramid.view import view_config
|
||||
from pyramid.response import Response
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="items", request_method="GET", renderer="json")
|
||||
def get_items_view(request) -> Dict[str, Any]:
|
||||
"""Retrieves a list of items."""
|
||||
return {"items": ["item1", "item2"]}
|
||||
|
||||
@view_config(route_name="items", request_method="POST", renderer="json")
|
||||
def create_item_view(request) -> Response:
|
||||
"""Creates a new item."""
|
||||
# ... create item logic ...
|
||||
return Response(json_body={"message": "Item created"}, status=201)
|
||||
```
|
||||
|
||||
### 2.2. Embrace Pyramid's Transaction Management
|
||||
|
||||
Utilize the transaction management system provided by Pyramid's cookiecutters (e.g., `pyramid_tm`). This ensures atomicity for database operations without manual `commit`/`rollback` in your view logic.
|
||||
|
||||
**❌ BAD - Manual Transaction Handling**
|
||||
```python
|
||||
from pyramid.view import view_config
|
||||
from myapp.models import DBSession, User
|
||||
|
||||
@view_config(route_name="register", request_method="POST", renderer="json")
|
||||
def register_user_view(request):
|
||||
try:
|
||||
user = User(name=request.json_body["name"])
|
||||
DBSession.add(user)
|
||||
DBSession.flush() # Manual flush
|
||||
DBSession.commit() # Manual commit
|
||||
return {"message": "User registered", "id": user.id}
|
||||
except Exception:
|
||||
DBSession.rollback() # Manual rollback
|
||||
raise
|
||||
```
|
||||
|
||||
**✅ GOOD - Automatic Transaction Handling (with `pyramid_tm`)**
|
||||
```python
|
||||
# Ensure pyramid_tm is configured in your __init__.py
|
||||
# config.include('pyramid_tm')
|
||||
|
||||
from pyramid.view import view_config
|
||||
from myapp.models import DBSession, User
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="register", request_method="POST", renderer="json")
|
||||
def register_user_view(request) -> Dict[str, Any]:
|
||||
"""Registers a new user, transaction handled automatically."""
|
||||
user = User(name=request.json_body["name"])
|
||||
DBSession.add(user)
|
||||
DBSession.flush() # Flush is fine, commit/rollback are handled by pyramid_tm
|
||||
return {"message": "User registered", "id": user.id}
|
||||
```
|
||||
|
||||
### 2.3. Avoid Mutable Global State and Singletons
|
||||
|
||||
Pyramid is designed to run multiple application instances in a single process. Avoid patterns that introduce mutable global state, which can lead to hard-to-debug side effects.
|
||||
|
||||
**❌ BAD - Global State**
|
||||
```python
|
||||
# myapp/settings.py (BAD practice)
|
||||
GLOBAL_CONFIG = {} # Mutable global dictionary
|
||||
|
||||
def initialize_config(app_settings):
|
||||
GLOBAL_CONFIG.update(app_settings)
|
||||
|
||||
# myapp/views.py
|
||||
from myapp.settings import GLOBAL_CONFIG
|
||||
|
||||
@view_config(route_name="config_info", renderer="json")
|
||||
def config_info_view(request):
|
||||
return {"global_setting": GLOBAL_CONFIG.get("some_setting")}
|
||||
```
|
||||
|
||||
**✅ GOOD - Pass Configuration via `request.registry.settings`**
|
||||
```python
|
||||
# myapp/__init__.py
|
||||
from pyramid.config import Configurator
|
||||
|
||||
def main(global_config, **settings):
|
||||
with Configurator(settings=settings) as config:
|
||||
# settings are automatically available via request.registry.settings
|
||||
pass
|
||||
return config.make_wsgi_app()
|
||||
|
||||
# myapp/views.py
|
||||
from pyramid.view import view_config
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="config_info", renderer="json")
|
||||
def config_info_view(request) -> Dict[str, Any]:
|
||||
"""Retrieves configuration information."""
|
||||
return {"some_setting": request.registry.settings.get("some_setting")}
|
||||
```
|
||||
|
||||
## 3. Type Hints
|
||||
|
||||
Always use type hints for functions, methods, and variables. This improves code readability, enables static analysis, and helps prevent runtime errors.
|
||||
|
||||
**❌ BAD - Untyped Code**
|
||||
```python
|
||||
def calculate_total(price, quantity):
|
||||
return price * quantity
|
||||
|
||||
class Product:
|
||||
def __init__(self, name, price):
|
||||
self.name = name
|
||||
self.price = price
|
||||
```
|
||||
|
||||
**✅ GOOD - Fully Typed Code**
|
||||
```python
|
||||
from typing import Union
|
||||
|
||||
def calculate_total(price: Union[int, float], quantity: int) -> Union[int, float]:
|
||||
"""Calculates the total price for a given quantity."""
|
||||
return price * quantity
|
||||
|
||||
class Product:
|
||||
def __init__(self, name: str, price: float):
|
||||
self.name = name
|
||||
self.price = price
|
||||
```
|
||||
|
||||
## 4. API Design
|
||||
|
||||
Design RESTful APIs with clear resources, HTTP verbs, and consistent response formats.
|
||||
|
||||
### 4.1. Consistent JSON Responses
|
||||
|
||||
Always return JSON for API endpoints, including error responses. Use `pyramid.response.Response` for custom status codes.
|
||||
|
||||
**❌ BAD - Inconsistent Error Responses**
|
||||
```python
|
||||
# Sometimes returns HTML, sometimes JSON, inconsistent error structure
|
||||
@view_config(route_name="data", renderer="json")
|
||||
def get_data_view(request):
|
||||
if not request.authenticated_userid:
|
||||
return Response("Unauthorized", status=401) # Returns plain text
|
||||
# ...
|
||||
return {"data": "some_data"}
|
||||
```
|
||||
|
||||
**✅ GOOD - Consistent JSON Responses**
|
||||
```python
|
||||
from pyramid.view import view_config
|
||||
from pyramid.response import Response
|
||||
from typing import Dict, Any
|
||||
|
||||
@view_config(route_name="data", request_method="GET", renderer="json")
|
||||
def get_data_view(request) -> Union[Dict[str, Any], Response]:
|
||||
"""Retrieves data, returns consistent JSON."""
|
||||
if not request.authenticated_userid:
|
||||
return Response(
|
||||
json_body={"error": "Unauthorized", "code": "AUTH_001"},
|
||||
status=401,
|
||||
)
|
||||
# ... logic to fetch data ...
|
||||
return {"data": "some_data"}
|
||||
```
|
||||
Reference in New Issue
Block a user