Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
Add flask skill for Python web applications
Jez075170ef3e69
diff --git a/skills/flask/README.md b/skills/flask/README.mdnew file mode 100644index 00000000..a173b40f--- /dev/null+++ b/skills/flask/README.md@@ -0,0 +1,88 @@+# Flask Skill++**Status**: Production Ready+**Last Updated**: December 2025++## Auto-Trigger Keywords++### Primary+- Flask+- Flask-SQLAlchemy+- Flask-Login+- Flask blueprints++### Secondary+- Python web app+- Jinja templates+- Flask factory pattern+- WSGI+- Werkzeug+- Flask-WTF++### Error-Based+- "circular import"+- "Working outside of application context"+- "cannot import name"+- "CSRF token is missing"+- "Could not build url for endpoint"++## What This Skill Does++Provides production-tested patterns for building Flask web applications:++- **Project Setup**: uv-based initialization+- **Structure**: Application factory pattern+- **Blueprints**: Modular route organization+- **Database**: Flask-SQLAlchemy integration+- **Authentication**: Flask-Login with forms+- **API Routes**: JSON endpoints+- **Testing**: pytest fixtures+- **Deployment**: Gunicorn patterns++## Known Issues Prevented++| Issue | Symptom | Prevention |+|-------|---------|------------|+| Circular imports | "cannot import name" | Extensions in separate file |+| Application context | "Working outside of application context" | Factory pattern + app_context |+| Blueprint routing | "Could not build url" | Correct url_for("blueprint.route") |+| CSRF errors | "CSRF token missing" | form.hidden_tag() in templates |+| Import order | Partial module init | Import routes at bottom of __init__.py |++## When to Use++- Creating Flask web applications+- Building traditional server-rendered apps+- Projects requiring Jinja templates+- Simple to medium complexity APIs+- When you prefer Flask over FastAPI++## When NOT to Use++- High-performance async APIs (use FastAPI)+- Already using FastAPI+- Microservices (consider FastAPI)+- Real-time applications (consider WebSockets frameworks)++## Version Info++| Package | Version |+|---------|---------|+| Flask | 3.1.2 |+| Flask-SQLAlchemy | 3.1.1 |+| Flask-Login | 0.6.3 |+| Flask-WTF | 1.2.2 |+| Werkzeug | 3.1.3 |++## Quick Start++```bash+uv init my-flask-app && cd my-flask-app+uv add flask flask-sqlalchemy flask-login flask-wtf python-dotenv+uv run flask --app app run --debug+```++## Resources++- `SKILL.md` - Full documentation+- `templates/` - Ready-to-use project filesdiff --git a/skills/flask/SKILL.md b/skills/flask/SKILL.mdnew file mode 100644index 00000000..a9a2c4eb--- /dev/null+++ b/skills/flask/SKILL.md@@ -0,0 +1,631 @@+---+name: flask+description: |+ Build Python web applications with Flask, using the application factory pattern, Blueprints,+ and Flask-SQLAlchemy. Covers project structure, authentication, and configuration management.++ Use when: creating Flask projects, organizing with blueprints, implementing authentication,+ or troubleshooting circular imports, application context errors, or blueprint registration.+---++# Flask Skill++Production-tested patterns for Flask with the application factory pattern, Blueprints, and Flask-SQLAlchemy.++**Latest Versions** (verified December 2025):+- Flask: 3.1.2+- Flask-SQLAlchemy: 3.1.1+- Flask-Login: 0.6.3+- Flask-WTF: 1.2.2+- Werkzeug: 3.1.3++---++## Quick Start++### Project Setup with uv++```bash+# Create project+uv init my-flask-app+cd my-flask-app++# Add dependencies+uv add flask flask-sqlalchemy flask-login flask-wtf python-dotenv++# Run development server+uv run flask --app app run --debug+```++### Minimal Working Example++```python+# app.py+from flask import Flask++app = Flask(__name__)+[email protected]("/")+def hello():+ return {"message": "Hello, World!"}++if __name__ == "__main__":+ app.run(debug=True)+```++Run: `uv run flask --app app run --debug`++---++## Project Structure (Application Factory)++For maintainable applications, use the factory pattern with blueprints:++```+my-flask-app/+├── pyproject.toml+├── config.py # Configuration classes+├── run.py # Entry point+│+├── app/+│ ├── __init__.py # Application factory (create_app)+│ ├── extensions.py # Flask extensions (db, login_manager)+│ ├── models.py # SQLAlchemy models+│ │+│ ├── main/ # Main blueprint+│ │ ├── __init__.py+│ │ └── routes.py+│ │+│ ├── auth/ # Auth blueprint+│ │ ├── __init__.py+│ │ ├── routes.py+│ │ └── forms.py+│ │+│ ├── templates/+│ │ ├── base.html+│ │ ├── main/+│ │ └── auth/+│ │+│ └── static/+│ ├── css/+│ └── js/+│+└── tests/+ ├── conftest.py+ └── test_main.py+```++---++## Core Patterns++### Application Factory++```python+# app/__init__.py+from flask import Flask+from app.extensions import db, login_manager+from config import Config+++def create_app(config_class=Config):+ """Application factory function."""+ app = Flask(__name__)+ app.config.from_object(config_class)++ # Initialize extensions+ db.init_app(app)+ login_manager.init_app(app)++ # Register blueprints+ from app.main import bp as main_bp+ from app.auth import bp as auth_bp++ app.register_blueprint(main_bp)+ app.register_blueprint(auth_bp, url_prefix="/auth")++ # Create database tables+ with app.app_context():+ db.create_all()++ return app+```++**Key Benefits**:+- Multiple app instances with different configs (testing)+- Avoids circular imports+- Extensions initialized once, bound to app later++### Extensions Module++```python+# app/extensions.py+from flask_sqlalchemy import SQLAlchemy+from flask_login import LoginManager++db = SQLAlchemy()+login_manager = LoginManager()+login_manager.login_view = "auth.login"+login_manager.login_message_category = "info"+```++**Why separate file?**: Prevents circular imports - models can import `db` without importing `app`.++### Configuration++```python+# config.py+import os+from dotenv import load_dotenv++load_dotenv()+++class Config:+ """Base configuration."""+ SECRET_KEY = os.environ.get("SECRET_KEY", "dev-secret-key")+ SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///app.db")+ SQLALCHEMY_TRACK_MODIFICATIONS = False+++class DevelopmentConfig(Config):+ """Development configuration."""+ DEBUG = True+++class TestingConfig(Config):+ """Testing configuration."""+ TESTING = True+ SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"+ WTF_CSRF_ENABLED = False+++class ProductionConfig(Config):+ """Production configuration."""+ DEBUG = False+```++### Entry Point++```python+# run.py+from app import create_app++app = create_app()++if __name__ == "__main__":+ app.run()+```++Run: `flask --app run run --debug`++---++## Blueprints++### Creating a Blueprint++```python+# app/main/__init__.py+from flask import Blueprint++bp = Blueprint("main", __name__)++from app.main import routes # Import routes after bp is created!+```++```python+# app/main/routes.py+from flask import render_template, jsonify+from app.main import bp++[email protected]("/")+def index():+ return render_template("main/index.html")++[email protected]("/api/health")+def health():+ return jsonify({"status": "ok"})+```++### Blueprint with Templates++```python+# app/auth/__init__.py+from flask import Blueprint++bp = Blueprint(+ "auth",+ __name__,+ template_folder="templates", # Blueprint-specific templates+ static_folder="static", # Blueprint-specific static files+)++from app.auth import routes+```++---++## Database Models++```python+# app/models.py+from datetime import datetime+from flask_login import UserMixin+from werkzeug.security import generate_password_hash, check_password_hash+from app.extensions import db, login_manager+++class User(UserMixin, db.Model):+ """User model for authentication."""+ __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(256), nullable=False)+ is_active = db.Column(db.Boolean, default=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ def set_password(self, password):+ self.password_hash = generate_password_hash(password)++ def check_password(self, password):+ return check_password_hash(self.password_hash, password)++ def __repr__(self):+ return f"<User {self.email}>"+++@login_manager.user_loader+def load_user(user_id):+ return User.query.get(int(user_id))+```++---++## Authentication with Flask-Login++### Auth Forms++```python+# app/auth/forms.py+from flask_wtf import FlaskForm+from wtforms import StringField, PasswordField, BooleanField, SubmitField+from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError+from app.models import User+++class LoginForm(FlaskForm):+ email = StringField("Email", validators=[DataRequired(), Email()])+ password = PasswordField("Password", validators=[DataRequired()])+ remember = BooleanField("Remember Me")+ submit = SubmitField("Login")+++class RegistrationForm(FlaskForm):+ email = StringField("Email", validators=[DataRequired(), Email()])+ password = PasswordField("Password", validators=[DataRequired(), Length(min=8)])+ confirm = PasswordField("Confirm Password", validators=[+ DataRequired(), EqualTo("password", message="Passwords must match")+ ])+ submit = SubmitField("Register")++ def validate_email(self, field):+ if User.query.filter_by(email=field.data).first():+ raise ValidationError("Email already registered.")+```++### Auth Routes++```python+# app/auth/routes.py+from flask import render_template, redirect, url_for, flash, request+from flask_login import login_user, logout_user, login_required, current_user+from app.auth import bp+from app.auth.forms import LoginForm, RegistrationForm+from app.extensions import db+from app.models import User++[email protected]("/register", methods=["GET", "POST"])+def register():+ if current_user.is_authenticated:+ return redirect(url_for("main.index"))++ form = RegistrationForm()+ if form.validate_on_submit():+ user = User(email=form.email.data)+ user.set_password(form.password.data)+ db.session.add(user)+ db.session.commit()+ flash("Registration successful! Please log in.", "success")+ return redirect(url_for("auth.login"))++ return render_template("auth/register.html", form=form)++[email protected]("/login", methods=["GET", "POST"])+def login():+ if current_user.is_authenticated:+ return redirect(url_for("main.index"))++ form = LoginForm()+ if form.validate_on_submit():+ user = User.query.filter_by(email=form.email.data).first()+ if user and user.check_password(form.password.data):+ login_user(user, remember=form.remember.data)+ next_page = request.args.get("next")+ flash("Logged in successfully!", "success")+ return redirect(next_page or url_for("main.index"))+ flash("Invalid email or password.", "danger")++ return render_template("auth/login.html", form=form)++[email protected]("/logout")+@login_required+def logout():+ logout_user()+ flash("You have been logged out.", "info")+ return redirect(url_for("main.index"))+```++### Protecting Routes++```python+from flask_login import login_required, current_user+[email protected]("/dashboard")+@login_required+def dashboard():+ return render_template("main/dashboard.html", user=current_user)+```++---++## API Routes (JSON)++For REST APIs without templates:++```python+# app/api/__init__.py+from flask import Blueprint++bp = Blueprint("api", __name__)++from app.api import routes+```++```python+# app/api/routes.py+from flask import jsonify, request+from flask_login import login_required, current_user+from app.api import bp+from app.extensions import db+from app.models import User++[email protected]("/users", methods=["GET"])+@login_required+def get_users():+ users = User.query.all()+ return jsonify([+ {"id": u.id, "email": u.email}+ for u in users+ ])++[email protected]("/users", methods=["POST"])+def create_user():+ data = request.get_json()+ if not data or "email" not in data or "password" not in data:+ return jsonify({"error": "Missing required fields"}), 400++ if User.query.filter_by(email=data["email"]).first():+ return jsonify({"error": "Email already exists"}), 409++ user = User(email=data["email"])+ user.set_password(data["password"])+ db.session.add(user)+ db.session.commit()++ return jsonify({"id": user.id, "email": user.email}), 201+```++Register with prefix:+```python+app.register_blueprint(api_bp, url_prefix="/api/v1")+```++---++## Critical Rules++### Always Do++1. **Use application factory pattern** - Enables testing, avoids globals+2. **Put extensions in separate file** - Prevents circular imports+3. **Import routes at bottom of blueprint `__init__.py`** - After `bp` is created+4. **Use `current_app` not `app`** - Inside request context+5. **Use `with app.app_context()`** - When accessing db outside requests++### Never Do++1. **Never import `app` in models** - Causes circular imports+2. **Never access `db` before app context** - RuntimeError+3. **Never store secrets in code** - Use environment variables+4. **Never use `app.run()` in production** - Use Gunicorn+5. **Never skip CSRF protection** - Keep Flask-WTF enabled++---++## Common Errors & Fixes++### Circular Import Error++**Error**: `ImportError: cannot import name 'X' from partially initialized module`++**Cause**: Models importing app, app importing models++**Fix**: Use extensions.py pattern:+```python+# WRONG - circular import+# app/__init__.py+from app.models import User # models.py imports db from here!++# RIGHT - deferred import+# app/__init__.py+def create_app():+ # ... setup ...+ from app.models import User # Import inside factory+```++### Working Outside Application Context++**Error**: `RuntimeError: Working outside of application context`++**Cause**: Accessing `current_app`, `g`, or `db` outside request++**Fix**:+```python+# WRONG+from app import create_app+app = create_app()+users = User.query.all() # No context!++# RIGHT+from app import create_app+app = create_app()+with app.app_context():+ users = User.query.all() # Has context+```++### Blueprint Not Found++**Error**: `werkzeug.routing.BuildError: Could not build url for endpoint`++**Cause**: Using wrong blueprint prefix in `url_for()`++**Fix**:+```python+# WRONG+url_for("login")++# RIGHT - include blueprint name+url_for("auth.login")+```++### CSRF Token Missing++**Error**: `Bad Request: The CSRF token is missing`++**Cause**: Form submission without CSRF token++**Fix**: Include token in templates:+```html+<form method="post">+ {{ form.hidden_tag() }} <!-- Adds CSRF token -->+ <!-- form fields -->+</form>+```++---++## Testing++```python+# tests/conftest.py+import pytest+from app import create_app+from app.extensions import db+from config import TestingConfig+++def app():+ app = create_app(TestingConfig)+ with app.app_context():+ db.create_all()+ yield app+ db.drop_all()+++def client(app):+ return app.test_client()+++def runner(app):+ return app.test_cli_runner()+```++```python+# tests/test_main.py+def test_index(client):+ response = client.get("/")+ assert response.status_code == 200+++def test_register(client):+ response = client.post("/auth/register", data={+ "email": "[email protected]",+ "password": "testpass123",+ "confirm": "testpass123",+ }, follow_redirects=True)+ assert response.status_code == 200+```++Run: `uv run pytest`++---++## Deployment++### Development+```bash+flask --app run run --debug+```++### Production with Gunicorn+```bash+uv add gunicorn+uv run gunicorn -w 4 -b 0.0.0.0:8000 "run:app"+```++### Docker+```dockerfile+FROM python:3.12-slim++WORKDIR /app+COPY . .++RUN pip install uv && uv sync++EXPOSE 8000+CMD ["uv", "run", "gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "run:app"]+```++### Environment Variables (.env)+```+SECRET_KEY=your-production-secret-key+DATABASE_URL=postgresql://user:pass@localhost/dbname+FLASK_ENV=production+```++---++## References++- [Flask Documentation](https://flask.palletsprojects.com/)+- [Flask-SQLAlchemy](https://flask-sqlalchemy.readthedocs.io/)+- [Flask-Login](https://flask-login.readthedocs.io/)+- [Flask Mega-Tutorial](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world)+- [Application Factory Pattern](https://flask.palletsprojects.com/en/stable/patterns/appfactories/)++---++**Last Updated**: December 2025+**Maintainer**: Jezweb | [email protected]diff --git a/skills/flask/templates/.env.example b/skills/flask/templates/.env.examplenew file mode 100644index 00000000..664f189f--- /dev/null+++ b/skills/flask/templates/.env.example@@ -0,0 +1,9 @@+# Flask configuration+FLASK_CONFIG=development+SECRET_KEY=your-super-secret-key-change-in-production++# Database+DATABASE_URL=sqlite:///app.db++# For production PostgreSQL:+# DATABASE_URL=postgresql://user:password@localhost/dbnamediff --git a/skills/flask/templates/app/__init__.py b/skills/flask/templates/app/__init__.pynew file mode 100644index 00000000..99b6c2e5--- /dev/null+++ b/skills/flask/templates/app/__init__.py@@ -0,0 +1,35 @@+"""Application factory for Flask app."""++from flask import Flask+from config import config+from app.extensions import db, login_manager+++def create_app(config_name="default"):+ """Create and configure the Flask application.++ Args:+ config_name: Configuration to use (development, testing, production)++ Returns:+ Configured Flask application instance+ """+ app = Flask(__name__)+ app.config.from_object(config[config_name])++ # Initialize extensions+ db.init_app(app)+ login_manager.init_app(app)++ # Register blueprints+ from app.main import bp as main_bp+ from app.auth import bp as auth_bp++ app.register_blueprint(main_bp)+ app.register_blueprint(auth_bp, url_prefix="/auth")++ # Create database tables+ with app.app_context():+ db.create_all()++ return appdiff --git a/skills/flask/templates/app/auth/__init__.py b/skills/flask/templates/app/auth/__init__.pynew file mode 100644index 00000000..680ddf66--- /dev/null+++ b/skills/flask/templates/app/auth/__init__.py@@ -0,0 +1,8 @@+"""Auth blueprint."""++from flask import Blueprint++bp = Blueprint("auth", __name__)++# Import routes after bp is created to avoid circular imports+from app.auth import routes # noqa: F401, E402diff --git a/skills/flask/templates/app/auth/forms.py b/skills/flask/templates/app/auth/forms.pynew file mode 100644index 00000000..d53792f4--- /dev/null+++ b/skills/flask/templates/app/auth/forms.py@@ -0,0 +1,35 @@+"""Authentication forms."""++from flask_wtf import FlaskForm+from wtforms import StringField, PasswordField, BooleanField, SubmitField+from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError+from app.models import User+++class LoginForm(FlaskForm):+ """User login form."""++ email = StringField("Email", validators=[DataRequired(), Email()])+ password = PasswordField("Password", validators=[DataRequired()])+ remember = BooleanField("Remember Me")+ submit = SubmitField("Log In")+++class RegistrationForm(FlaskForm):+ """User registration form."""++ email = StringField("Email", validators=[DataRequired(), Email()])+ password = PasswordField(+ "Password",+ validators=[DataRequired(), Length(min=8, message="Password must be at least 8 characters")]+ )+ confirm = PasswordField(+ "Confirm Password",+ validators=[DataRequired(), EqualTo("password", message="Passwords must match")]+ )+ submit = SubmitField("Register")++ def validate_email(self, field):+ """Check if email is already registered."""+ if User.query.filter_by(email=field.data).first():+ raise ValidationError("This email is already registered.")diff --git a/skills/flask/templates/app/auth/routes.py b/skills/flask/templates/app/auth/routes.pynew file mode 100644index 00000000..ba1a5000--- /dev/null+++ b/skills/flask/templates/app/auth/routes.py@@ -0,0 +1,54 @@+"""Authentication routes."""++from flask import render_template, redirect, url_for, flash, request+from flask_login import login_user, logout_user, login_required, current_user+from app.auth import bp+from app.auth.forms import LoginForm, RegistrationForm+from app.extensions import db+from app.models import User++[email protected]("/register", methods=["GET", "POST"])+def register():+ """User registration."""+ if current_user.is_authenticated:+ return redirect(url_for("main.index"))++ form = RegistrationForm()+ if form.validate_on_submit():+ user = User(email=form.email.data)+ user.set_password(form.password.data)+ db.session.add(user)+ db.session.commit()+ flash("Registration successful! Please log in.", "success")+ return redirect(url_for("auth.login"))++ return render_template("auth/register.html", form=form)++[email protected]("/login", methods=["GET", "POST"])+def login():+ """User login."""+ if current_user.is_authenticated:+ return redirect(url_for("main.index"))++ form = LoginForm()+ if form.validate_on_submit():+ user = User.query.filter_by(email=form.email.data).first()+ if user and user.check_password(form.password.data):+ login_user(user, remember=form.remember.data)+ next_page = request.args.get("next")+ flash("Welcome back!", "success")+ return redirect(next_page or url_for("main.index"))+ flash("Invalid email or password.", "danger")++ return render_template("auth/login.html", form=form)++[email protected]("/logout")+@login_required+def logout():+ """User logout."""+ logout_user()+ flash("You have been logged out.", "info")+ return redirect(url_for("main.index"))diff --git a/skills/flask/templates/app/extensions.py b/skills/flask/templates/app/extensions.pynew file mode 100644index 00000000..5f67f1d2--- /dev/null+++ b/skills/flask/templates/app/extensions.py@@ -0,0 +1,17 @@+"""Flask extensions initialization.++Extensions are initialized without app binding here to avoid circular imports.+They are bound to the app in the application factory (create_app).+"""++from flask_sqlalchemy import SQLAlchemy+from flask_login import LoginManager++# Database+db = SQLAlchemy()++# Login manager+login_manager = LoginManager()+login_manager.login_view = "auth.login"+login_manager.login_message = "Please log in to access this page."+login_manager.login_message_category = "info"diff --git a/skills/flask/templates/app/main/__init__.py b/skills/flask/templates/app/main/__init__.pynew file mode 100644index 00000000..53909f0f--- /dev/null+++ b/skills/flask/templates/app/main/__init__.py@@ -0,0 +1,8 @@+"""Main blueprint."""++from flask import Blueprint++bp = Blueprint("main", __name__)++# Import routes after bp is created to avoid circular imports+from app.main import routes # noqa: F401, E402diff --git a/skills/flask/templates/app/main/routes.py b/skills/flask/templates/app/main/routes.pynew file mode 100644index 00000000..f40a3e42--- /dev/null+++ b/skills/flask/templates/app/main/routes.py@@ -0,0 +1,24 @@+"""Main blueprint routes."""++from flask import render_template, jsonify+from flask_login import login_required, current_user+from app.main import bp++[email protected]("/")+def index():+ """Home page."""+ return render_template("main/index.html")++[email protected]("/dashboard")+@login_required+def dashboard():+ """User dashboard - requires authentication."""+ return render_template("main/dashboard.html", user=current_user)++[email protected]("/api/health")+def health():+ """Health check endpoint."""+ return jsonify({"status": "ok"})diff --git a/skills/flask/templates/app/models.py b/skills/flask/templates/app/models.pynew file mode 100644index 00000000..d529be9f--- /dev/null+++ b/skills/flask/templates/app/models.py@@ -0,0 +1,35 @@+"""Database models."""++from datetime import datetime+from flask_login import UserMixin+from werkzeug.security import generate_password_hash, check_password_hash+from app.extensions import db, login_manager+++class User(UserMixin, db.Model):+ """User model for authentication."""++ __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(256), nullable=False)+ is_active = db.Column(db.Boolean, default=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ def set_password(self, password):+ """Hash and set the user's password."""+ self.password_hash = generate_password_hash(password)++ def check_password(self, password):+ """Check if the provided password matches the hash."""+ return check_password_hash(self.password_hash, password)++ def __repr__(self):+ return f"<User {self.email}>"+++@login_manager.user_loader+def load_user(user_id):+ """Load user by ID for Flask-Login."""+ return User.query.get(int(user_id))diff --git a/skills/flask/templates/config.py b/skills/flask/templates/config.pynew file mode 100644index 00000000..0393dda5--- /dev/null+++ b/skills/flask/templates/config.py@@ -0,0 +1,51 @@+"""Application configuration classes."""++import os+from dotenv import load_dotenv++load_dotenv()+++class Config:+ """Base configuration."""++ SECRET_KEY = os.environ.get("SECRET_KEY", "dev-secret-key-change-in-production")+ SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///app.db")+ SQLALCHEMY_TRACK_MODIFICATIONS = False+++class DevelopmentConfig(Config):+ """Development configuration."""++ DEBUG = True+ SQLALCHEMY_ECHO = True+++class TestingConfig(Config):+ """Testing configuration."""++ TESTING = True+ SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"+ WTF_CSRF_ENABLED = False+++class ProductionConfig(Config):+ """Production configuration."""++ DEBUG = False++ @classmethod+ def init_app(cls, app):+ """Production-specific initialization."""+ # Ensure SECRET_KEY is set+ assert cls.SECRET_KEY != "dev-secret-key-change-in-production", \+ "Set SECRET_KEY environment variable for production!"+++# Config mapping+config = {+ "development": DevelopmentConfig,+ "testing": TestingConfig,+ "production": ProductionConfig,+ "default": DevelopmentConfig,+}diff --git a/skills/flask/templates/pyproject.toml b/skills/flask/templates/pyproject.tomlnew file mode 100644index 00000000..6554d729--- /dev/null+++ b/skills/flask/templates/pyproject.toml@@ -0,0 +1,26 @@+[project]+name = "my-flask-app"+version = "0.1.0"+description = "Flask web application"+readme = "README.md"+requires-python = ">=3.11"+dependencies = [+ "flask>=3.1.0",+ "flask-sqlalchemy>=3.1.0",+ "flask-login>=0.6.3",+ "flask-wtf>=1.2.0",+ "python-dotenv>=1.0.0",+ "email-validator>=2.0.0",+]++[project.optional-dependencies]+dev = [+ "pytest>=8.0.0",+ "pytest-cov>=4.0.0",+]+prod = [+ "gunicorn>=21.0.0",+]++[tool.pytest.ini_options]+testpaths = ["tests"]diff --git a/skills/flask/templates/run.py b/skills/flask/templates/run.pynew file mode 100644index 00000000..3265f71e--- /dev/null+++ b/skills/flask/templates/run.py@@ -0,0 +1,10 @@+"""Application entry point."""++import os+from app import create_app++config_name = os.environ.get("FLASK_CONFIG", "development")+app = create_app(config_name)++if __name__ == "__main__":+ app.run()diff --git a/skills/flask/templates/tests/__init__.py b/skills/flask/templates/tests/__init__.pynew file mode 100644index 00000000..d4839a6b--- /dev/null+++ b/skills/flask/templates/tests/__init__.py@@ -0,0 +1 @@+# Tests packagediff --git a/skills/flask/templates/tests/conftest.py b/skills/flask/templates/tests/conftest.pynew file mode 100644index 00000000..c1f69b23--- /dev/null+++ b/skills/flask/templates/tests/conftest.py@@ -0,0 +1,40 @@+"""Pytest fixtures for Flask testing."""++import pytest+from app import create_app+from app.extensions import db+from app.models import User+++def app():+ """Create application for testing."""+ app = create_app("testing")++ with app.app_context():+ db.create_all()+ yield app+ db.drop_all()+++def client(app):+ """Test client for making requests."""+ return app.test_client()+++def runner(app):+ """Test CLI runner."""+ return app.test_cli_runner()+++def user(app):+ """Create a test user."""+ with app.app_context():+ user = User(email="[email protected]")+ user.set_password("testpassword123")+ db.session.add(user)+ db.session.commit()+ return userdiff --git a/skills/flask/templates/tests/test_auth.py b/skills/flask/templates/tests/test_auth.pynew file mode 100644index 00000000..094e4f24--- /dev/null+++ b/skills/flask/templates/tests/test_auth.py@@ -0,0 +1,42 @@+"""Tests for authentication routes."""+++def test_register_page(client):+ """Test registration page loads."""+ response = client.get("/auth/register")+ assert response.status_code == 200+++def test_login_page(client):+ """Test login page loads."""+ response = client.get("/auth/login")+ assert response.status_code == 200+++def test_register_user(client):+ """Test user registration."""+ response = client.post("/auth/register", data={+ "email": "[email protected]",+ "password": "testpass123",+ "confirm": "testpass123",+ }, follow_redirects=True)+ assert response.status_code == 200+++def test_login_user(client, user):+ """Test user login."""+ response = client.post("/auth/login", data={+ "email": "[email protected]",+ "password": "testpassword123",+ }, follow_redirects=True)+ assert response.status_code == 200+++def test_login_invalid_password(client, user):+ """Test login with wrong password."""+ response = client.post("/auth/login", data={+ "email": "[email protected]",+ "password": "wrongpassword",+ })+ assert response.status_code == 200+ assert b"Invalid email or password" in response.datadiff --git a/skills/flask/templates/tests/test_main.py b/skills/flask/templates/tests/test_main.pynew file mode 100644index 00000000..3cd6aae8--- /dev/null+++ b/skills/flask/templates/tests/test_main.py@@ -0,0 +1,21 @@+"""Tests for main routes."""+++def test_index(client):+ """Test home page loads."""+ response = client.get("/")+ assert response.status_code == 200+++def test_health(client):+ """Test health endpoint."""+ response = client.get("/api/health")+ assert response.status_code == 200+ assert response.json["status"] == "ok"+++def test_dashboard_requires_login(client):+ """Test dashboard redirects to login when not authenticated."""+ response = client.get("/dashboard")+ assert response.status_code == 302+ assert "/auth/login" in response.location