flask▌
jezweb/claude-skills · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
Production-tested Flask patterns with application factory, Blueprints, and SQLAlchemy, preventing 9 documented errors.
- ›Covers application factory pattern, extension initialization, blueprint organization, and database models to avoid circular imports and context errors
- ›Prevents known issues including stream_with_context teardown regressions, async/gevent conflicts, CSRF cache interference, and Flask-Login session protection edge cases
- ›Includes authentication patterns with Flask-Login
Flask Skill
Production-tested patterns for Flask with the application factory pattern, Blueprints, and Flask-SQLAlchemy.
Latest Versions (verified January 2026):
- Flask: 3.1.2
- Flask-SQLAlchemy: 3.1.1
- Flask-Login: 0.6.3
- Flask-WTF: 1.2.2
- Werkzeug: 3.1.5
- Python: 3.9+ required (3.8 dropped in Flask 3.1.0)
Quick Start
Project Setup with uv
# 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
# app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return {"message": "Hello, World!"}
if __name__ == "__main__":
app.run(debug=True)
Run: uv run flask --app app run --debug
Known Issues Prevention
This skill prevents 9 documented issues:
Issue #1: stream_with_context Teardown Regression (Flask 3.1.2)
Error: KeyError in teardown functions when using stream_with_context
Source: GitHub Issue #5804
Why It Happens: Flask 3.1.2 introduced a regression where stream_with_context triggers teardown_request() calls multiple times before response generation completes. If teardown callbacks use g.pop(key) without a default, they fail on the second call.
Prevention:
# WRONG - fails on second teardown call
@app.teardown_request
def _teardown_request(_):
g.pop("hello") # KeyError on second call
# RIGHT - idempotent teardown
@app.teardown_request
def _teardown_request(_):
g.pop("hello", None) # Provide default value
Status: Will be fixed in Flask 3.2.0 as side effect of PR #5812. Until then, ensure all teardown callbacks are idempotent.
Issue #2: Async Views with Gevent Incompatibility
Error: RuntimeError when handling concurrent async requests with gevent
Source: GitHub Issue #5881
Why It Happens: Asgiref fails when gevent monkey-patching is active. Asyncio expects a single event loop per OS thread, but gevent's monkey-patching makes threading.Thread create greenlets instead of real threads, causing both loops to run on the same physical thread and block each other.
Prevention: Choose either async (with asyncio/uvloop) OR gevent, not both. If you must use both:
import asyncio
import gevent.monkey
import gevent.selectors
from flask import Flask
gevent.monkey.patch_all()
loop = asyncio.EventLoop(gevent.selectors.DefaultSelector())
gevent.spawn(loop.run_forever)
class GeventFlask(Flask):
def async_to_sync(self, func):
def run(*args, **kwargs):
coro = func(*args, **kwargs)
future = asyncio.run_coroutine_threadsafe(coro, loop)
return future.result()
return run
app = GeventFlask(__name__)
Note: This "defeats the whole purpose of both" (maintainer comment). Individual async requests work, but concurrent requests fail without this workaround.
Issue #3: Test Client Session Not Updated on Redirect
Error: Session state incorrect after follow_redirects=True in tests
Source: GitHub Issue #5786
Why It Happens: In Flask < 3.1.2, the test client's session wasn't correctly updated after following redirects.
Prevention:
# If using Flask >= 3.1.2, follow_redirects works correctly
def test_login_redirect(client):
response = client.post('/login',
data={'email': '[email protected]', 'password': 'pass'},
follow_redirects=True)
assert 'user_id' in session # Works in 3.1.2+
# For Flask < 3.1.2, make separate requests
response = client.post('/login', data={...})
assert response.status_code == 302
response = client.get(response.location) # Explicit redirect follow
Status: Fixed in Flask 3.1.2. Upgrade to latest version.
Issue #4: Application Context Lost in Threads (Community-sourced)
Error: RuntimeError: Working outside of application context in background threads
Source: Sentry.io Guide
Why It Happens: When passing current_app to a new thread, you must unwrap the proxy object using _get_current_object() and push app context in the thread.
Prevention:
from flask import current_app
import threading
# WRONG - current_app is a proxy, loses context in thread
def background_task():
app_name = current_app.name # Fails!
@app.route('/start')
def start_task():
thread = threading.Thread(target=background_task)
thread.start()
# RIGHT - unwrap proxy and push context
def background_task(app):
with app.app_context():
app_name = app.name # Works!
@app.route('/start')
def start_task():
app = current_app._get_current_object()
thread = threading.Thread(target=background_task, args=(app,))
thread.start()
Verified: Common pattern in production applications, documented in official Flask docs.
Issue #5: Flask-Login Session Protection Unexpected Logouts (Community-sourced)
Error: Users logged out unexpectedly when IP address changes Source: Flask-Login Docs Why It Happens: Flask-Login's "strong" session protection mode deletes the entire session if session identifiers (like IP address) change. This affects users on mobile networks or VPNs.
Prevention:
# app/extensions.py
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.session_protection = "basic" # Default, less strict
# login_manager.session_protection = "strong" # Strict, may logout on IP change
# login_manager.session_protection = None # Disabled (not recommended)
Note: By default, Flask-Login allows concurrent sessions (same user on multiple browsers). To prevent this, implement custom session tracking.
Verified: Official Flask-Login documentation, multiple 2024 blog posts.
Issue #6: CSRF Protection Cache Interference (Community-sourced)
Error: Form submissions fail with "CSRF token missing/invalid" on cached pages
Source: Flask-WTF Docs
Why It Happens: If webserver cache policy caches pages longer than WTF_CSRF_TIME_LIMIT, browsers serve cached pages with expired CSRF tokens.
Prevention:
# Option 1: Align cache duration with token lifetime
WTF_CSRF_TIME_LIMIT = None # Never expire (less secure)
# Option 2: Exclude forms from cache
@app.after_request
def add_cache_headers(response):
if request.method == 'GET' and 'form' in request.endpoint:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
# Option 3: Configure webserver to not cache POST targets
# In Nginx: add "proxy_cache_bypass $cookie_session" for form routes
Verified: Official Flask-WTF documentation warning, security best practices guides from 2024.
Issue #7: Per-Request max_content_length Override (New Feature)
Feature: Flask 3.1.0 added ability to customize Request.max_content_length per-request
Source: Flask 3.1.0 Release Notes
Usage:
from flask import Flask, request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGHow to use flask on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add flask
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches flask from GitHub repository jezweb/claude-skills and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate flask. Access the skill through slash commands (e.g., /flask) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
User Story & Requirements Generation
Create detailed user stories, acceptance criteria, and feature specs
Example
Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios
Reduce spec writing time by 50%, ensure comprehensive coverage
Competitive Analysis
Research competitors, compare features, identify gaps
Example
Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities
Complete competitive research in 2 hours instead of 2 days
Roadmap Prioritization
Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs
Example
Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale
Make data-driven prioritization decisions faster
Stakeholder Communication
Draft PRDs, status updates, and stakeholder presentations
Example
Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement
Save 3-5 hours/week on communication overhead
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client
- ›Access to product documentation and roadmap tools (Jira, Notion, etc.)
- ›Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
- ›Stakeholder contact information and communication channels
Time Estimate
30-60 minutes to see productivity improvements
Installation Steps
- 1.Install product management skill
- 2.Start with user story generation for known feature
- 3.Progress to competitive analysis: research 2-3 competitors
- 4.Use for roadmap prioritization: apply RICE/ICE scoring
- 5.Draft stakeholder communications and refine based on feedback
- 6.Build template library for recurring PM tasks
- 7.Share effective prompts with product team
Common Pitfalls
- ⚠Not validating competitive research—verify facts before sharing
- ⚠Accepting user stories without involving engineering team
- ⚠Over-relying on frameworks without qualitative judgment
- ⚠Not customizing outputs to company culture and communication style
- ⚠Skipping stakeholder validation of generated requirements
Best Practices▌
✓ Do
- +Validate research and competitive analysis with real data
- +Collaborate with engineering when generating technical requirements
- +Customize frameworks and templates to your company context
- +Use skill for first drafts, refine with stakeholder input
- +Document successful prompt patterns for PM tasks
- +Combine AI efficiency with human judgment and intuition
✗ Don't
- −Don't publish competitive analysis without fact-checking
- −Don't finalize user stories without engineering review
- −Don't make prioritization decisions solely on AI scoring
- −Don't skip customer validation of generated requirements
- −Don't ignore company-specific context and culture
💡 Pro Tips
- ★Provide context: company goals, constraints, customer feedback
- ★Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
- ★Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
- ★Use skill for 70% generation + 30% customization to company needs
When to Use This▌
✓ Use When
Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.
✗ Avoid When
Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.
Learning Path▌
- 1Basic: user stories, feature specs, status updates
- 2Intermediate: competitive analysis, prioritization frameworks, PRDs
- 3Advanced: product strategy, go-to-market planning, OKR setting
- 4Expert: product vision, market positioning, business model innovation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.6★★★★★67 reviews- ★★★★★Sofia Bansal· Dec 28, 2024
flask fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Naina Kapoor· Dec 28, 2024
flask reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Hana Diallo· Dec 20, 2024
Registry listing for flask matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Yuki Rao· Dec 8, 2024
Solid pick for teams standardizing on skills: flask is focused, and the summary matches what you get after install.
- ★★★★★Naina Shah· Dec 8, 2024
flask is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Aditi Jackson· Dec 4, 2024
Registry listing for flask matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★William Abbas· Nov 27, 2024
We added flask from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Carlos Sanchez· Nov 23, 2024
Useful defaults in flask — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Maya Wang· Nov 19, 2024
flask has been reliable in day-to-day use. Documentation quality is above average for community skills.
- ★★★★★Hana Jain· Nov 19, 2024
Keeps context tight: flask is the kind of skill you can hand to a new teammate without a long onboarding doc.
showing 1-10 of 67