Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Redline

flask-redline

The Flask + SQLAlchemy adapter for Redline: a request profiler and backend analyzer. Every request becomes a trace with a span timeline, the SQL it ran, N+1 and duplicate-query detection with concrete fix diffs, one-click EXPLAIN, optional flamegraphs, and a fast web UI served from your own app.

from flask import Flask
from sqlalchemy import create_engine
from flask_redline import Redline

app = Flask(__name__)
engine = create_engine("sqlite:///app.db")

# access="local": localhost only (unset, Redline answers 404 outside debug mode)
Redline(app, engine=engine, settings={"access": "local"})  # UI at http://localhost:5000/_redline/

With Flask-SQLAlchemy you do not even pass the engine: its engines (including SQLALCHEMY_BINDS) are found and instrumented automatically.

db = SQLAlchemy(app)
Redline(app)

Traces are stored in their own SQLite file (.redline/redline.db), never in your database.

Install

pip install --pre flask-redline
pip install "flask[async]"      # only if you use `async def` views

Published packages are available on PyPI. This checkout describes development v0.4; installed behavior depends on the released version. Docs: https://pythondeveloper6.github.io/redline/.

For flamegraphs install the adapter's profile extra: pip install --pre "flask-redline[profile]".

Python 3.10+, Flask 3.0+, SQLAlchemy 2.x.

Redline

Redline(
    app=None,
    *,
    engine=None,          # Engine | [engines] | {"alias": engine} (default: Flask-SQLAlchemy's)
    settings=None,        # dict | redline_core.Settings
    url_prefix=None,      # default: the mount_path setting, else "/_redline"
    permission=None,      # callable(request) -> bool (see "Access control")
    store=None,           # custom Store (default: SQLite file at storage_path)
)
redline.init_app(app)     # application factories

What it does:

  • wraps app.wsgi_app in a WSGI middleware that times the request and records status, headers and (size-capped) bodies;
  • connects Flask hooks for the route template (/orders/<int:order_id>), the view function, templates and unhandled errors;
  • instruments the engines;
  • registers a blueprint with the UI and JSON API under url_prefix, and the flask redline command group.

settings takes any Redline setting with case-insensitive keys. They can also live in app.config["REDLINE"] (a dict); keys passed to Redline win. A Settings instance passed to Redline is used as-is.

Redline(app, engine=engine, settings={
    "sample_rate": 0.1,                 # keep 10% of requests ...
    "always_keep_slower_than_ms": 300,  # ... plus every slow one and every error
    "slow_query_ms": 50,
})

Application factory

redline = Redline(engine=engine)

def create_app():
    app = Flask(__name__)
    redline.init_app(app)
    return app

redline.store, .settings, .engines, .add_engine(engine, alias=None) and .close() act on the current app (inside an app context) or on the last app initialised. The store is flushed and closed at interpreter exit.

Engines

The first engine of a list is the "default" db alias; others are named after their database file, or pass a dict. The alias is stored on each query so EXPLAIN runs on the right engine.

Redline(app, engine=[main_engine, analytics_engine])
Redline(app, engine={"main": main_engine, "analytics": analytics_engine})
redline.add_engine(late_engine)            # an engine created later

When engine is omitted and Flask-SQLAlchemy 3.x is set up on the app, its engines are discovered on the first request (they may not exist yet when Redline(app) runs), named default and after each bind key.

What is recorded

  • Request / response: method, path, route template, view dotted name, status, headers, query string and body. Secrets are redacted by the core (Authorization, cookies, password/token/card keys...).
  • Bodies are never consumed or buffered unboundedly. The request body is copied as the view reads it; response bodies, including streams, are kept only up to max_body_bytes. A stream_with_context generator is not read ahead, and the trace ends when the last chunk is sent, so its work counts towards the latency. send_file and anything the server serves through wsgi.file_wrapper (direct_passthrough) is handed back untouched: only its size is recorded.
  • SQL through before/after_cursor_execute: statement, bound params (redacted), duration, rowcount, vendor, executemany, db_alias, and the project line that issued the query.
  • Spans: a view span around the view function (not the before_request hooks), and a template span per render_template / render_template_string; queries a template triggers (lazy loading) nest under it.
  • Unhandled exceptions are recorded (Flask's got_request_exception) and re-raised or turned into a 500 exactly as before. abort(404) and other 4xx HTTPExceptions are client errors, not failures: the trace has no error, and always_keep_errors does not keep it. A 5xx status is an error.
  • async def views (Flask's asgiref bridge) keep the trace: queries and spans created inside the coroutine land in the request's trace. Work that starts a bare threading.Thread is not attributed to any request.
  • Your own spans: with redline_core.span("pricing.compute"): ... (also as a decorator).
  • X-Redline-Run: <id>;step=<n> becomes tags (used by the load tester).
  • X-Redline-Check: <id>;req=<i>;n=<k> becomes tags (used by redline check, only for a check run that exists in the store).
  • Requests under url_prefix are never recorded.

If you put werkzeug.middleware.proxy_fix.ProxyFix (or any other WSGI middleware) around the app, wrap after creating Redline so the recorded client address is the real one. Apps mounted under a SCRIPT_NAME (DispatcherMiddleware) record the full path and route.

Outbound HTTP (opt-in)

Nothing is patched unless you ask:

from flask_redline import instrument_httpx, instrument_requests

instrument_httpx()      # every httpx.Client / AsyncClient call becomes an http_out span
instrument_requests()   # same for requests.Session.send (needs `requests` installed)

URLs are redacted (?api_key=... is masked). uninstrument_httpx() and uninstrument_requests() undo it.

Profiling

Flamegraphs are opt-in per request: add ?_redline=profile or the header X-Redline-Profile: 1 (needs the [profile] extra).

Fix suggestions

For an N+1, SQLAlchemyFixSuggester maps the repeated query back to your models and tells you how to eager-load it:

Repeated query Suggestion
child table filtered by its foreign key selectinload(Parent.children)
parent looked up by primary key, once per row joinedload(Child.parent)
association (secondary) table filtered by the parent selectinload(Parent.tags)

It then walks the call stack to find the select(Parent) or session.query(Parent) in your source and produces a real unified diff. This works the same with Flask-SQLAlchemy's db.session and db.Model. When the statement cannot be located you get the one-line code hint with lower confidence instead.

Access control

The UI exposes your SQL, request bodies and EXPLAIN, so treat it like an admin tool.

Default. With no permission, the access setting decides (default local, served only in debug mode until you set access): only loopback clients (127.0.0.0/8, ::1; unix sockets only with trust_unix_socket) that address the server by a loopback name (Host: localhost, 127.0.0.1, [::1], any port; this blocks DNS rebinding) are served, and a warning is logged at startup. Refusals are JSON {"error": {"code": "forbidden", "message"}}. Add other host names with the allowed_hosts setting. A loopback peer sending X-Forwarded-For without being in trusted_proxies is refused; behind a reverse proxy use access="token" and trusted_proxies. Tokens, basic auth, allowed_ips and read_only are described in the access control docs.

Your own check. permission is any callable(request) -> bool, called with Flask's request; passing it implies access="framework" and replaces the loopback default, so the Host check becomes yours (the core gate still applies allowed_ips, read_only, features and CSRF).

from flask_login import current_user

Redline(app, engine=engine, permission=lambda request: current_user.is_admin)

Raise werkzeug.exceptions.abort(401) (or any HTTPException) inside it to answer with that status; it is rendered as {"error": {"code": "unauthorized", ...}}, keeping a WWW-Authenticate header.

CSRF. Every non-GET request is refused with 403 csrf_failed when it carries Sec-Fetch-Site: cross-site or same-site, or an Origin (including null) that does not match the request host. Browsers always send Origin on those methods, so another website cannot drive your Redline through a logged-in browser. Non-browser clients (curl, scripts) send no Origin and are only subject to the access policy.

Redline's own responses carry X-Frame-Options: DENY.

EXPLAIN

POST /_redline/api/explain runs EXPLAIN for a recorded SELECT on the engine it came from (matched by db_alias) inside a transaction that is always rolled back (and READ ONLY on PostgreSQL). EXPLAIN ANALYZE executes the query, so it is off unless explain_analyze=True.

Command line

flask redline clear [--yes]                          # delete every recorded trace
flask redline prune [--max-age-days N] [--max-rows N]   # apply retention now (0 disables a rule)

Development

uv sync --all-packages
cd packages/flask-redline && uv run pytest

A runnable demo with deliberately bad views lives in examples/flask.

v0.4 real-world workflows

The next release adds:

  • Handled SQL failures with vendor/SQLSTATE/native-code classification, raw rowcounts, failed-attempt counts and stable issue groups, even when the application returns HTTP 200.
  • SQL Server estimated plans, guarded actual-plan collection and catalog candidates; explicit engine ownership, optional all-engine observation and observed session-state evidence.
  • Offline redline check-sql for supported raw-SQL Python shapes, JSON/JUnit reports, baselines, explicit compile checks and schema snapshots. Static checks are conservative.
  • Generic background jobs, stages, row outcomes, retries and optional Celery signals; a Jobs page and commit-before-failure evidence for investigating partial job completion.
  • SQL value policies, privacy profiles, route rules, request/user correlation and redaction preview.
  • Bounded capture, failure-safe observation, storage auditing, read-only worker-store browsing, and explicit sanitized OTLP summary export.

Use these to investigate a caught database error, a migration that broke raw SQL, a worker that committed before failing, an N+1 endpoint, or a performance refactor whose responses must remain equivalent. The UI exposes SQL evidence, jobs, offline SQL checks and privacy preview alongside the existing timelines, plans, profiles and refactor reports.

For production choose the record-and-inspect preset, private storage and authenticated access. Replay, load/refactor runs, source analysis and database plan execution are disabled by default there. Live MySQL/SQL Server drivers, broker/prefork behavior and the intended filesystem/deployment must be qualified before rollout; fixture tests do not establish compatibility with every codebase.

See the detailed workflow guide, production guide and feature catalog.

Please test Redline on a real development or staging project and open an issue for bugs or feature requests. Include framework/database/driver versions and a small sanitized reproduction. Never post credentials or private recordings; follow the security policy for vulnerabilities.

License

MIT

Metadata

Release files for flask-redline 0.5.0b2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-redline 0.5.0b2
File Size Uploaded Provenance Actions
flask_redline-0.5.0b2.tar.gz 48.5 kB With provenance Details for flask_redline-0.5.0b2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flask-redline 0.5.0b2
File Interpreter ABI Platform Actions
flask_redline-0.5.0b2-py3-none-any.whl Python 3 none any Details for flask_redline-0.5.0b2-py3-none-any.whl

Total release size: 79.1 kB

Release files / flask_redline-0.5.0b2.tar.gz

Download URL flask_redline-0.5.0b2.tar.gz
Size 48.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4d40536ee34d59a122bc43ee9db0581e12aa1a2074a342d55b625e829184a21e
BLAKE2b-256 checksum
How to use checksums
5aaf309ffa4e1fd823513a14322559aba1dc2bdf038f71fa2050fdd7df47cc0c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / flask_redline-0.5.0b2-py3-none-any.whl

Download URL flask_redline-0.5.0b2-py3-none-any.whl
Size 30.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bebf285892806a43d95f8cb4683ce53c7f58e745f6bee3c543f280b660a6ebf1
BLAKE2b-256 checksum
How to use checksums
ab7760ad4a193d4d2e838434ca9b7955420e9a0e59f766c2afd34e81af7f43d0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for flask-redline 0.5.0b2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for flask_redline-0.5.0b2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page