Skip to content
All posts

A Django CSV export that keeps the last good file

Build a Django management command for scheduled CSV exports. Break it after one row and check exactly what the next reader finds on disk.

A stock dashboard reads products.csv every morning. Last night’s export failed after one product. This morning the dashboard opens the file, parses the header and the product, and reports success. Where did the rest of the catalog go?

If another process depends on a CSV at a fixed path, write the new export beside the old file, close it, then replace the old file. Don’t open the published path for writing until you’re prepared to lose its contents. Here’s a Django management command and a failure test that shows why checking “can I parse this CSV?” isn’t enough.

Decide who asks for the export

A scheduled command fits when one producer owns the file and a downstream program knows where to find it. But if a person expects “export what I’m looking at,” a nightly file can give them the wrong rows even when the job succeeds. InvenTree, for example, applies the table’s filters, search and sort order to its export. That’s a different contract from “every product, ordered by SKU.”

If users request individual reports that take time to prepare, consider a third design. pretix separates starting an export from downloading the result. Two people can ask for different reports without agreeing on what products.csv means. The command below is for a shared local snapshot, not an implementation of either project’s exporter.

Write the CSV without touching the published path

Suppose an installed Django app called inventory has a migrated Product model with two text fields: sku (unique) and name. Add inventory/management/commands/export_products.py, with empty __init__.py files in management/ and commands/. That layout is how Django discovers management commands.

import csv
import os
from pathlib import Path
from tempfile import NamedTemporaryFile

from django.core.management.base import BaseCommand

from inventory.models import Product


def product_rows():
    return Product.objects.order_by("sku").values_list("sku", "name").iterator()


class Command(BaseCommand):
    help = "Replace a local product CSV only after all rows are written."

    def add_arguments(self, parser):
        parser.add_argument("destination", type=Path)

    def handle(self, *args, **options):
        destination = Path(options["destination"])
        staged = None
        try:
            with NamedTemporaryFile(
                mode="w", encoding="utf-8", newline="",
                dir=destination.parent, delete=False,
            ) as output:
                staged = Path(output.name)
                writer = csv.writer(output)
                writer.writerow(("sku", "name"))
                writer.writerows(product_rows())
            os.replace(staged, destination)
        finally:
            if staged is not None:
                staged.unlink(missing_ok=True)

Run python manage.py export_products /path/to/exports/products.csv. Supply an existing directory writable by the job. The argument is a filename, not shell redirection: > products.csv would let the shell truncate the very file you want to preserve.

Three choices in the command matter:

  • Select the columns explicitly. The header says sku,name, so the queryset yields those two fields in that order. Sorting by the unique SKU gives the consumer a stable order for unchanged data. Use the same filter every run if the file represents a subset rather than the whole catalog.
  • Give the CSV writer a text file opened with newline="". Let Python’s CSV module handle quoting and record terminators. A comma in a product name isn’t a third column; a newline inside a quoted name isn’t a new product.
  • Keep the temporary file in the destination directory. A named temporary file gives the command a private staging path. Closing the file before calling os.replace() means even an error flushing the write prevents publication. On POSIX, successful replacement is atomic; putting both paths on the same filesystem avoids a cross-filesystem rename failure.

Break the producer after one row

We ran the command with Python 3.11.2, Django 5.2.14 and SQLite 3.40.1. We inserted SKU B2 with the name Blue, large, followed by A1 with a literal newline between Green and small. Reading the successful export with csv.reader gave these records, shown as Python strings:

[['sku', 'name'], ['A1', 'Green\nsmall'], ['B2', 'Blue, large']]

Then we replaced the row source with a generator that yielded one product and raised. To reproduce the check in an inventory test with an empty test database:

import csv
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch

from django.core.management import call_command


from inventory.models import Product

Product.objects.create(sku="B2", name="Blue, large")
Product.objects.create(sku="A1", name="Green\nsmall")


def interrupted_rows():
    yield 'X1', 'partial'
    raise RuntimeError('interrupted after one row')


with TemporaryDirectory() as folder:
    dest = Path(folder) / 'products.csv'
    call_command('export_products', str(dest))
    with dest.open(encoding="utf-8", newline="") as stream:
        assert list(csv.reader(stream)) == [
            ["sku", "name"], ["A1", "Green\nsmall"], ["B2", "Blue, large"],
        ]
    before = dest.read_bytes()
    with patch('inventory.management.commands.export_products.product_rows', interrupted_rows):
        try:
            call_command('export_products', str(dest))
        except RuntimeError as err:
            assert str(err) == 'interrupted after one row'
        else:
            raise AssertionError('The export should have failed')
    assert dest.read_bytes() == before
    assert list(dest.parent.iterdir()) == [dest]

What the next reader found: with staging, the previous CSV was byte-for-byte unchanged and no temporary file remained. In a control run we opened the destination itself in w mode and passed the same failing generator to writer.writerows() after writing the header. The reader got [['sku', 'name'], ['X1', 'partial']]. No parser error. The file looked like a plausible one-product catalog. A successful retry restored the original bytes.

The failure test checks the producer’s promise: an interrupted run must not publish half its work. The consumer may need other checks. For example, Built with Rust’s qsv validation exercise shows duplicate IDs passing both a structural check and the supplied row schema. If a valid delivery needs a particular set of SKUs, compare against that set; counting physical lines will already give the wrong answer for our two-product fixture.

What the file swap doesn’t guarantee

If a previous run succeeded, an error before replacement leaves an old but complete export. A failed first run leaves no published file. If freshness matters, alert on the job’s last successful completion rather than treating “file exists” as proof it ran last night. Decide separately whether a successful query returning zero rows should publish a header-only file. This command does; a catalog that must never be empty should reject that result before replacement.

Use a trusted directory. Replacement publishes the temporary file with its own permissions; it does not inherit the previous file’s access mode. Test the read as the actual consumer account. If two jobs overlap, the last replacement wins, not necessarily the newest query. Serialize the jobs if order matters.

Finally, a file swap isn’t a database transaction, a power-loss durability guarantee, or an object-storage upload protocol. The test exercised a Python exception, not a killed process; abrupt termination can leave a staging file behind. For this local handoff the acceptance test is narrower and worth keeping: after a failed export, open the exact path the next reader will open and compare its contents with the last successful delivery.

More from Built with Django