anantbhandarkar/make-it-right/mir-backend-python-flask

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (Flask module). Flask 3.1 + Werkzeug 3.1 specific reliability augmentation. Use alongside the mir-backend skill when the target stack is Flask — it carries the mechanical footguns that the framework-agnostic skill deliberately omits: app/request context misuse (current_app/request/g outside a context, background threads, Celery tasks), missing input validation and object-level authorization, SQLAlchemy session scoping and teardown, the app-factory pattern and circular imports, offloading heavy work to Celery/RQ, Flask 3.1 config safety (SECRET_KEY_FALLBACKS key rotation, TRUSTED_HOSTS after the SERVER_NAME behaviour change, MAX_CONTENT_LENGTH / MAX_FORM_MEMORY_SIZE / MAX_FORM_PARTS, debug-mode RCE), Alembic migration safety via Flask-Migrate, and Flask's own 2026 advisories. TRIGGER only when the Python backend stack is Flask — building, reviewing, or debugging a Flask route, blueprint, extension, SQLAlchemy session, or Flask-Migrate revision. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-python (CPython runtime concerns: GIL, async/sync, fork-safety, cold start, packaging supply chain); this module only adds Flask library mechanics. SKIP for Django (mir-backend-python-django), FastAPI (mir-backend-python-fastapi), Quart or any other non-Flask stack, and non-Python runtimes.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-python-flask

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-python-flask.

/mir-backend-python-flask · Make It Right (Flask)

Bottom tier of the chain: mir-backend (generic gates) → mir-backend-python (CPython runtime model) → this (Flask library mechanics). Run the gates first; load the Python runtime tier for the concurrency/process model; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (GIL, async-vs-sync, blocking the event loop, fork-safe pools, cold start) live in `mir-backend-python` — not here.

Stack assumed, versions verified 13 Aug 2026: Flask 3.1.3 (released 18 Feb 2026; requires Python ≥3.9) · Werkzeug 3.1.8 · Flask-SQLAlchemy over SQLAlchemy 2.0.52 · PostgreSQL · Flask-Migrate / Alembic 1.19.1 · Celery or RQ for background work. If the project uses bare SQLAlchemy with a scoped_session instead of Flask-SQLAlchemy, apply the session-scoping rules directly — the pattern is the same, the scaffold differs. Flask 3.1 changed `SERVER_NAME` semantics and added several limit settings — see item 6; a codebase written against 3.0 has a real gap.

The Flask footguns AI walks into most

These are the stack-specific cousins of the failure-mode catalog. Each is something Flask code gets wrong even when the logic is right.

1. App and request context — the three magic proxies and where they die

current_app, request, and g are context-local proxies that only resolve inside an active application or request context. Using them at import time, in a module-level expression, or in a background thread/task raises RuntimeError: Working outside of application context or RuntimeError: Working outside of request context. AI writes context-access code at class-definition time or in a threading.Thread target and ships a crash that never surfaces in a single-threaded dev run.

`current_app` — resolves to the app bound on the current context. Access it inside a view function, a CLI command, or after explicitly pushing a context.

`g` — scratch space on the application context, which is pushed and popped around each request. It is torn down at the end of each request. Do not use g as an inter-request cache or to share state between requests — each request gets a fresh g, and each worker process has its own.

Background threads: any thread spawned from a request has no context. Push one explicitly:

python
# WRONG — raises RuntimeError in the thread
def background():
result = some_db_query() # uses current_app implicitly
thread = threading.Thread(target=background)
thread.start()
# RIGHT
app = current_app._get_current_object() # get the real app, not the proxy
def background(app):
with app.app_context():
result = some_db_query()
thread = threading.Thread(target=background, args=(app,))
thread.start()

If the thread genuinely needs the request (not just the app), flask.copy_current_request_context wraps the callable — but a thread that outlives the response and still reads request is a design smell; copy the values you need instead.

Celery/RQ tasks: same issue — tasks run in a worker process with no Flask context unless the task sets one up. The standard pattern is a ContextTask base class that pushes app.app_context() before calling the task body.

2. Unopinionated by design — validation and authorization are easy to forget

Flask has no built-in request validation, no enforced authentication scheme, and no object-level permission model. AI builds a route that parses request.json directly and applies business logic, forgetting both layers. The result is a service that accepts malformed input and happily returns another user's data.

Input validation: use Pydantic (v2 model_validate) or marshmallow to parse and validate request bodies before they touch the business layer. Never use raw request.json.get("field") for fields that have type or range constraints. Note request.get_json() raises a 415 if the content type isn't JSON and a 400 on malformed JSON — decide which you want rather than letting the default surprise the client.

python
from pydantic import BaseModel, ConfigDict, ValidationError
class CreateOrderBody(BaseModel):
model_config = ConfigDict(extra="forbid") # unknown fields are a client bug, not a silent drop
product_id: int
quantity: int
@app.post("/orders")
def create_order():
try:
body = CreateOrderBody.model_validate(request.get_json())
except ValidationError as e:
abort(422, description=e.errors())
...

Object-level authorization (IDOR): decorating a route with @login_required (flask-login) confirms the caller is authenticated; it does not confirm the caller owns the resource being loaded. Always assert ownership after loading the object:

python
@app.get("/orders/<int:order_id>")
@login_required
def get_order(order_id):
order = db.get_or_404(Order, order_id)
if order.user_id != current_user.id:
abort(404) # 404 not 403 — 403 confirms the row exists
return order_schema.dump(order)

Better still, scope the query so the row is invisible: db.one_or_404(db.select(Order).filter_by(id=order_id, user_id=current_user.id)).

3. SQLAlchemy session scoping — leaked sessions corrupt state

A Session is a unit of work bound to a single connection. Sharing one session across requests or threads corrupts it — you get stale data, DetachedInstanceError, or silent cross-request data bleed.

Flask-SQLAlchemy handles scoping automatically: db.session is a scoped_session keyed on the current app context. It is removed in teardown_appcontext — you do not need to manage the lifecycle manually. The corollary is that touching db.session from a background thread with no app context raises RuntimeError: Working outside of application context — it does not quietly hand you a second session. Push a context (with app.app_context():) and let it exit so the session is removed, or move the work to a real worker.

Bare SQLAlchemy: if you're not using Flask-SQLAlchemy, create a scoped_session and register teardown explicitly:

python
from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker(bind=engine))
@app.teardown_appcontext
def shutdown_session(exception):
Session.remove() # returns the session to the pool and clears the scope

Commit/rollback boundary must be explicit. Flask-SQLAlchemy does not autocommit. Call db.session.commit() when the work should persist; if an exception propagates, call db.session.rollback(). Teardown will roll back an unfinished transaction, which is correct — but an explicit rollback in an except block is clearer and it is the only way to keep working with the session afterwards.

python
@app.post("/transfer")
def transfer():
try:
from_acct.balance -= amount
to_acct.balance += amount
db.session.commit()
except Exception:
db.session.rollback()
raise

Pool sizing is per worker process. Total connections = gunicorn workers × (pool_size + max_overflow). The pool belongs to the Engine, which belongs to the process — threads inside a worker share it, they do not each get one, so do not multiply by the thread count. What threads change is contention: more threads than pool_size + max_overflow means requests block on pool_timeout instead of on the database. This is how a small Flask service exhausts Postgres max_connections. Set SQLALCHEMY_ENGINE_OPTIONS deliberately, including pool_pre_ping=True if anything between you and the database drops idle connections.

4. Blueprint organization and the app factory — avoid import-time global state

A module-level app = Flask(__name__) and extensions bound directly to it at import time (db = SQLAlchemy(app)) create a global singleton that makes testing impossible (you can't swap config between tests), causes circular imports as blueprints try to import from the module that imports them, and builds the connection pool before the server forks its workers — which is the fork-safety bug in mir-backend-python.

App factory pattern: create_app(config=None) instantiates the app, configures it, calls extension.init_app(app), and registers blueprints — all inside the function. Extensions are created at module level but bound to the app lazily via init_app:

python
# extensions.py — no app reference at module level
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# factory.py
from .extensions import db
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(config or "config.ProductionConfig")
db.init_app(app)
from .orders import orders_bp
app.register_blueprint(orders_bp, url_prefix="/orders")
return app

Circular imports: blueprints that import db from extensions.py (not from the app module) break the cycle. Never import from the factory module inside a blueprint.

Testing: each test calls create_app("config.TestingConfig"), so isolation is trivial. A global app singleton makes this impossible without monkey-patching config.

5. Heavy and durable work — Flask workers block

Flask runs one request per thread. A route that does a 30-second video encode, a large data export, or a third-party API call with no timeout blocks that worker for the duration, reducing throughput to workers - 1 for all other requests. Every outbound HTTP call needs an explicit timeout= — requests has no default and will wait forever.

Offload to Celery or RQ:

  • The route creates the job record, enqueues the task with an idempotency key, and returns 202 Accepted with a job ID.
  • The worker executes the task; its result is stored in the DB or Redis.
  • The client polls or receives a webhook.
python
@app.post("/exports")
def start_export():
job = ExportJob(user_id=current_user.id, status="queued")
db.session.add(job)
db.session.commit() # commit BEFORE enqueue
run_export.apply_async(args=[job.id], task_id=str(job.id))
return {"job_id": job.id}, 202

Order matters: enqueue after the commit, or the worker can pick the job up and query for a row that doesn't exist yet — and win the race often enough to look intermittent.

Idempotency: Celery tasks must be re-delivery safe. Store the outcome keyed on the job ID; a retry that finds a completed record returns without re-executing. This is the at-least-once / idempotency rule from mir-backend landing in Flask's Celery integration.

Flask's async support: async def route handlers work but require the flask[async] extra, and Flask is still WSGI. Each async view is run through asgiref.async_to_sync in a fresh event loop for that request. Consequences: there is no shared loop, so you cannot hold an async connection pool or an httpx.AsyncClient across requests; you get correctness and no I/O concurrency; and background tasks created with create_task die when the loop closes at the end of the request. True async concurrency means Quart or a different framework. The runtime-level async/sync decision lives in mir-backend-python; here the point is only that Flask's async def does not give you a free event loop.

6. Config in Flask 3.1 — what changed and what to set

Flask 3.1 added several settings that a 3.0-era codebase does not have, and changed one behaviour that silently widens the app's exposure.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-python-flask/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-python-flask)

Something wrong with this skill or its page? Tell us.