Skip to content

Tracked exports (export permission, export log, export = what's on screen)

By default an admin list's Export button (CSV / JSON) has three gaps:

  • Anyone who can see a list can export all of it. SQLAdmin has no separate export permission, so a role with only the list (index) permission can download every row, including PII.
  • Nothing records it. Create / update / delete are in the activity log; an export is none of those.
  • It isn't what's on screen. The Export links carry no query string, and the export ignores the search box, SQLAdmin's own filters and the sort order. (kloudmint's cf_<column> filters work only if the URL is typed by hand.)

Turn on tracked exports and all three are fixed. It is opt-in: with none of the options below, a project behaves exactly as before.

Set it up

from kloudmint import Kloudmint, create_file_export_model, FileExportAdminBase

FileExport = create_file_export_model(Base)        # then an Alembic migration for the table

class FileExportAdmin(FileExportAdminBase, model=FileExport):
    pass

admin = Kloudmint(
    app, engine, auth_backend=...,
    file_export_model=FileExport,       # record every export
    require_export_permission=True,     # export needs the `export` permission
    export_max_rows=50_000,             # optional cap per export (0 = no cap, the default)
)
admin.register(..., FileExportAdmin)

Each option works on its own. file_export_model needs a synchronous SQLAlchemy engine for now.

Turn the permission on safely

require_export_permission=True adds an export action to every exportable view, and it appears as a column in the role permission grid. Roles that can export today lose export until they are granted it, so grant it first, for example in your seed script, or give your admin role export on every resource, then switch the option on. A view with can_export = False never offers or accepts export, whatever a role holds.

What gets recorded

One row per export that is allowed to start. A request refused with a 403 (no export permission, or can_export = False) is not recorded, and nothing is sent:

Column
resource, identity The permission resource (Candidate) and the URL slug
format csv or json
filters The exact query string: search, filters, sort
status in_progress, then success or failed
row_count Rows exported
exported_by_id, exported_by_email Who asked
error_message Class and a short message if it failed (never the full text: that can contain row data)
created_at, completed_at When

The outcome is the real one: success is written only after the whole file has been sent, and an interrupted download (the user closes the tab) is recorded as failed.

An export that cannot be recorded does not happen. If the table is missing or the database refuses the write, the export fails before any row is read. A missing migration therefore shows up at once, and no unrecorded download of personal data can happen.

The Exports screen

FileExportAdminBase is a read-only Exports page in the sidebar (no create, edit or delete, and it cannot itself be exported).

  • A user sees only their own exports.
  • The all permission (a column in the role grid for FileExport) shows everyone's, which is what an auditor needs. Opening someone else's export by id gives a 404 without it.

Export = what is on screen

With the feature on, the Export button carries the page's query string, and the export applies the same list_query, SQLAdmin filters, sort and search as the list. Soft-deleted rows, ChildOf hiding and column filters apply too. An export of a candidate's certificates from a filtered list contains those certificates only.

The Export button is hidden from roles without the export permission.

Exporting only the ticked rows

SQLAdmin's own bulk actions (delete, custom actions) act on the rows you tick, but its Export always exported every row of the list: the Export links carried no selection. With tracked exports on, they do:

  • Rows ticked: the button reads Export (3 selected), its links carry the ticked row ids (pks=), and the export contains exactly those rows.
  • Nothing ticked: it exports every row matching the current search and filters, across all pages, as before. A hint on the button says which of the two will happen. (Not with a required selection.)
  • The selection survives paging. Ticks are remembered in the browser (per list, search and filter) while you move between pages, so ticking rows on page 1 and then on page 3 exports all of them. A bar above the table shows the count and a Clear selection link. Up to 500 rows can be picked by hand.
  • Select all matching rows. Ticking the header box offers Select all N matching rows (every row of the current search and filters, on every page). Choosing it turns the button into Export (all N); the boxes lock until you clear it.

The selection narrows the export on top of the view's own query, filters and search, so a ticked row the view would not show you can never be exported by guessing ids. The export record stores the selection in filters (pks=...), so the Exports screen shows exactly which rows were exported. It works for CSV, JSON and XLSX, for composite primary keys, and for background exports (the selection decides whether the export is big enough to be queued). A malformed selection, or more than 1000 ids, is refused with a 400 before anything is recorded.

Requiring a selection

By default, with nothing ticked, Export exports every row matching the current search and filters. If you would rather nobody can export a whole table by accident (or on purpose), switch on a required selection:

admin = Kloudmint(app, engine, auth_backend=..., file_export_model=FileExport,
                  export_requires_selection=True)
  • In the browser the Export button is greyed out and reads Export (select rows) until at least one row is ticked; ticking rows turns it into Export (3 selected). Clicking it while locked does nothing.
  • On the server an export request without ticked rows is refused with a 400 ("Select the rows you want to export first"), before anything is recorded. This is the real control: the button is only a convenience, because anyone can type the export URL. Filters and search alone are not a selection.
  • The export permission is checked first, so someone without it still gets a 403.
  • A selection can span pages, and Select all matching rows is a deliberate choice that exports the whole filtered list (select_all=1). Without it the cap is 1000 ids per export. select_all stops accidents, not determined users: the export permission and export_max_rows are the real access controls. It still works with background exports.

Background exports

On a big table an export built during the request is slow, holds a web worker, and can hit a browser or proxy timeout. With background exports on, an export of more rows than a threshold is queued instead:

  1. The click records a queued row and sends the user to the Exports screen ("Export #7 is being prepared").
  2. A job re-runs the view's own query as that user, writes the file in batches, saves it through your storage backend, and marks the row success (or failed, with the reason).
  3. The Exports screen refreshes itself while something is pending, then shows a download link and an expiry.

At or under the threshold nothing changes: the export streams during the request, exactly as in the previous section. The threshold counts the rows left after search, filters and the row cap.

from kloudmint import Kloudmint, ExportBackground, purge_expired
from kloudmint.storage import S3Storage            # or LocalStorage (see below)

admin = Kloudmint(
    app, engine, auth_backend=...,
    file_export_model=FileExport,                  # required
    storage=S3Storage(bucket="private-exports"),   # required (here, or in ExportBackground(storage=...))
    export_background=ExportBackground(
        threshold=5000,       # more rows than this -> background
        expires_days=7,       # how long a finished file can be downloaded
        # runner=ThreadRunner()      the default; see "Runners"
        # notify=send_ready_email    optional, called with the export row after success
    ),
)

Roles that export large tables also need the Exports screen (FileExport index, plus show): a queued export is only useful to someone who can open it. A user without it gets the instant export instead.

Where the job runs: runners

Runner Use it when
ThreadRunner(max_workers=2) (default) You have no job queue. Runs on a small thread pool inside the web process. A restart loses running jobs; they are marked failed the next time the Exports screen is opened.
CeleryRunner(task) You already run Celery (pip install kloudmint[tasks]). Your task calls run_export.
your own Any object with submit(admin, export_id).
InlineRunner() Tests only: it runs the job before the request returns.
# app/tasks.py -- a Celery worker needs to import your admin (its views, auth backend and storage)
@celery_app.task
def export_task(export_id):
    from app.admin import admin          # the Kloudmint instance your web app builds
    run_export(admin, export_id)

ExportBackground(runner=CeleryRunner(export_task))

The job runs as the user who asked: it loads them again through your auth backend's load_user, re-checks their export permission, and runs the view's own list_query, filters, sort and search from a snapshot of the original request (the query string and the user). A user who was deleted, or lost the permission, between the click and the job gets a failed export, not a file. Code in your own list_query or formatters that reads other parts of the request will not find them in the job.

Storage: use a private one

Finished files hold personal data. Give exports their own private storage:

  • S3Storage: a private bucket. The download route redirects to a short-lived signed URL.
  • LocalStorage: the download route streams the file after checking who is asking. Do not serve the directory with StaticFiles (that is what public_path is for); anything under a public mount is readable without a login.

Both built-in backends upload from a path, so a large file is never read into memory. A custom backend works too: with only upload(bytes, name) the whole file passes through memory once.

Downloads, expiry and clean-up

Files are downloaded from the Exports screen at /<exports identity>/<id>/download: the person who exported it (or an all holder), never cached, and never after expires_at (HTTP 410). Expiry stops the download; the file is deleted by purge_expired, which you run on a schedule:

purge_expired(admin)    # from cron or Celery beat; returns how many files it removed. The records stay.

Failures

What happened What the row says
The job could not be queued (broker down) failed: "Could not queue the export: ..."
Building the file raised failed with the exception class and a short message
The user is gone or lost the permission failed: "...no longer exists" / "...no longer permitted"
The worker died failed after stale_after_minutes (default 60): "The worker restarted or timed out..."

Excel (xlsx)

Excel is opt-in per view and needs one extra package:

pip install "kloudmint[xlsx]"
class CandidateAdmin(RBACModelView, model=Candidate):
    export_types = ["csv", "json", "xlsx"]

The Export menu then offers XLSX. Numbers, booleans and dates stay numbers and dates in Excel; other values become text; empty values are empty cells; control characters Excel rejects are dropped. The sheet is written one row at a time, so large ones stay flat in memory. XLSX follows the same permission, record, search/filters and background rules as CSV and JSON. Without the extra installed, the failure says what to install.

Limits

  • Needs a synchronous SQLAlchemy engine for the export record and the job.
  • Instant exports (at or under the threshold) are still built during the request, with the rows loaded into memory first: export_max_rows is the guard. JSON is written as a stream in the background but not in an instant export.
  • Only SQLAdmin's own export route is covered; a custom export view you wrote yourself is not recorded.
  • A queued export needs the requester to be able to open the Exports screen (see above).