Comprehensive Python development standards for Flask applications with SQLite, Docker healthchecks, and Git workflow enforcement
A comprehensive rule set for Python development with Flask, SQLite, Docker, and modern development practices. Enforces git commits, Docker healthchecks, and industry-standard patterns.
This skill enforces best practices for Python development with Flask applications, SQLite databases, and containerized deployments. It ensures proper project structure, code quality, security, testing, and operational reliability through mandatory git workflows and Docker healthchecks.
**YOU MUST commit ALL changes to git.** This is NON-NEGOTIABLE.
After making ANY file modifications:
1. **Stage changes**: Run `git add <modified-files>` or `git add .`
2. **Commit immediately**: Run `git commit -m "type: descriptive message"`
3. **Verify success**: Confirm the commit succeeded with no errors
4. **Use conventional commit format**:
- `fix:` for bug fixes
- `feat:` for new features
- `refactor:` for code refactoring
- `docs:` for documentation changes
- `chore:` for maintenance tasks
- `test:` for test changes
**Example**: `git commit -m "feat: add user authentication with Google OAuth"`
**NEVER** skip commits. **NEVER** summarize changes without committing. Every modification must be committed before the task is complete.
**ALL Docker services MUST have comprehensive healthchecks.**
**FORBIDDEN practices:**
**REQUIRED practices:**
**Proper healthcheck example:**
```yaml
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://127.0.0.1:8080/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
labels:
deunhealth.restart.on.unhealthy: "true"
```
**If disabling healthchecks seems like a "fix", find the ROOT CAUSE instead.**
Organize projects using modern Python src-layout:
```
project/
├── src/
│ └── package_name/
│ ├── __init__.py
│ ├── app.py (Flask factory)
│ ├── models.py
│ ├── routes/
│ │ ├── __init__.py
│ │ ├── auth.py (Blueprint)
│ │ └── api.py (Blueprint)
│ ├── types.py
│ └── utils.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ └── test_routes.py
├── config/
│ └── settings.py
├── static/
├── templates/
├── requirements.txt
├── pyproject.toml
└── README.md
```
**Key principles:**
**Apply Black formatting and follow PEP 8:**
- `snake_case` for functions and variables
- `PascalCase` for classes
- `UPPER_CASE` for constants
**Example:**
```python
from typing import Optional
from flask import Blueprint, request
MAX_RETRY_COUNT = 3
class UserService:
def get_user_by_id(self, user_id: int) -> Optional[dict]:
pass
```
**Use comprehensive type hints:**
**Example:**
```python
from typing import Optional, Protocol
def fetch_user(user_id: int) -> Optional[dict]:
"""Fetch user by ID."""
pass
```
**Use Flask factory pattern with Blueprints:**
**Factory pattern example:**
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config.from_object('config.settings')
db.init_app(app)
from .routes import auth_bp, api_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(api_bp, url_prefix='/api')
return app
```
**Use SQLAlchemy ORM with proper practices:**
**Model example:**
```python
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False, index=True)
password_hash = db.Column(db.String(255), nullable=False)
```
**Implement secure authentication:**
**Example:**
```python
from flask_login import LoginManager, UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
login_manager = LoginManager()
class User(UserMixin, db.Model):
def set_password(self, password: str) -> None:
self.password_hash = generate_password_hash(password)
def check_password(self, password: str) -> bool:
return check_password_hash(self.password_hash, password)
```
**Build RESTful APIs with proper standards:**
**Example:**
```python
from flask import Blueprint, jsonify, request
api_bp = Blueprint('api', __name__)
@api_bp.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id: int):
user = User.query.get_or_404(user_id)
return jsonify({'id': user.id, 'email': user.email}), 200
```
**Write comprehensive tests with pytest:**
**Example:**
```python
import pytest
from src.app import create_app
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_home(client):
response = client.get('/')
assert response.status_code == 200
```
**Follow OWASP and Flask security best practices:**
**Example:**
```python
from flask import Flask
from flask_cors import CORS
app = create_app()
CORS(app, resources={r"/api/*": {"origins": "https://example.com"}})
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
```
**Optimize application performance:**
**Caching example:**
```python
from flask_caching import Cache
cache = Cache(config={'CACHE_TYPE': 'simple'})
@cache.cached(timeout=60)
def get_users():
return User.query.all()
```
**Implement robust error handling:**
**Example:**
```python
import logging
logger = logging.getLogger(__name__)
@app.errorhandler(404)
def not_found(error):
logger.warning(f"404 error: {request.url}")
return jsonify({'error': 'Not found'}), 404
```
**Maintain comprehensive documentation:**
**Docstring example:**
```python
def fetch_user(user_id: int) -> Optional[dict]:
"""Fetch user by ID from the database.
Args:
user_id: The unique identifier for the user.
Returns:
A dictionary containing user data, or None if not found.
Raises:
DatabaseError: If the database connection fails.
"""
pass
```
**Follow modern development practices:**
**Virtual environment setup:**
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
```
**Manage dependencies properly:**
**Example `requirements.txt`:**
```
Flask==2.3.2
Flask-SQLAlchemy==3.0.5
Flask-Login==0.6.2
bcrypt==4.0.1
pytest==7.4.0
```
This skill enforces production-ready Python Flask development with:
**Remember:** Every code change MUST be committed to git, and every Docker service MUST have working healthchecks. No exceptions.
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-flask-and-sqlite-best-practices/raw