Skip to content

Instantly share code, notes, and snippets.

@isoboroff
Created February 18, 2021 14:08
Show Gist options
  • Save isoboroff/94d61bb5c84890a0126a1a6ee7c42093 to your computer and use it in GitHub Desktop.
Save isoboroff/94d61bb5c84890a0126a1a6ee7c42093 to your computer and use it in GitHub Desktop.
A minimal Django custom storage backend to use GitPython to store revisions to uploaded files and disallow deletes
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.files.base import File
from django.utils.deconstruct import deconstructible
from git import Repo
import io
@deconstructible
class VersionedStorage(FileSystemStorage):
def __init__(self, option=None):
super().__init__()
if not option and hasattr(settings, 'VERSIONED_STORAGE_OPTIONS'):
option = settings.VERSIONED_STORAGE_OPTIONS
try:
self.repo = Repo(path=settings.MEDIA_ROOT)
except:
self.repo = Repo.init(path=settings.MEDIA_ROOT)
# using FileSystemStorage._open(name, mode)
def _save(self, name, content):
saved_name = super()._save(name, content)
self.repo.index.add(saved_name)
self.repo.index.commit(name)
return saved_name
def delete(self, name):
raise NotImplementedError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment