Skip to content

Misc. Django scripts

Dolsy Smith edited this page May 16, 2023 · 2 revisions

Finding exports older than a certain date

from ui.models import *
from datetime import datetime
from pathlib import Path
import csv

DATE_MIN = datetime(2022, 9, 1)
OUTFILE = f'/sfm-export-data/exports-{DATE_MIN.isoformat()}.csv'

# Find exports earlier than specified date
exports = Export.objects.filter(date_ended__lt=DATE_MIN)

# Get file sizes
file_stat = []
for export in exports:
    root = Path(export.path)
    if root.exists():
        stat = [{'file': f.name,
                 'parent': f.parent,
                 'size': f.stat().st_size,
                 'export_date': export.date_ended,
                 'export_id': export.export_id} for f in root.glob('**/*') 
                 if f.is_file()]
        file_stat.extend(stat)

# To export a CSV of exports
with open(OUTFILE, 'w') as f:
    writer = csv.DictWriter(f, fieldnames=file_stat[0].keys())
    writer.writeheader()
    for row in file_stat:
        writer.writerow(row)

# To delete exports (and files on disk)
for export in exports:
    export.delete()