bethaus-app/migrate_cache.py
2025-04-18 20:39:30 +00:00

64 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
migrate_cache.py
Migrate DiskCache caches from “old” inmemory entries (bytes, mime) into
“new” ondisk read=True entries so that Flask can send them via send_file(path).
Usage:
python migrate_cache.py /path/to/filecache_audio \
/path/to/filecache_image \
/path/to/filecache_video \
/path/to/filecache_other
"""
import io
import sys
from diskcache import Cache
def migrate_cache(cache_path):
"""
Walks every key in the cache at `cache_path`. If the value is a tuple of
(bytes, mime), rewrites it via read=True so DiskCache stores it as a file.
"""
print(f"➡ Migrating cache at {cache_path!r}")
cache = Cache(cache_path)
migrated = 0
skipped = 0
# Iterate keys without loading everything into memory
for key in cache.iterkeys():
try:
val = cache.get(key)
except Exception as e:
print(f" [ERROR] key={key!r} get failed: {e}")
continue
# Detect oldstyle entries: (bytes, mime)
if (
isinstance(val, tuple)
and len(val) == 2
and isinstance(val[0], (bytes, bytearray))
and isinstance(val[1], str)
):
data, mime = val
buf = io.BytesIO(data)
buf.seek(0)
# Restore as an ondisk file
cache.set(key, buf, read=True)
migrated += 1
else:
skipped += 1
cache.close()
print(f" → Done: migrated={migrated}, skipped={skipped}\n")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: migrate_cache.py <cache_dir1> [<cache_dir2> ...]")
sys.exit(1)
for directory in sys.argv[1:]:
migrate_cache(directory)