Friday, March 04, 2016

Python/Django Storage Backend Notes

Inspired by:
https://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#storage

Interacting directly with storage backend
from django.conf import settings
from django.core.files.storage import get_storage_class
STORAGE_CLASS_STRING = getattr(settings, "MY_STORAGE_CLASS",  \
        settings.DEFAULT_FILE_STORAGE)
sc = get_storage_class(STORAGE_CLASS_STRING)
s = sc()
s.url("jjj-test/JOE.jpg")
# '/media/jjj-test/JOE.jpg'
s.path("jjj-test/JOE.jpg")
# u'/home/jjasinski/Sites/mysite/htdocs/media/jjj-test/JOE.jpg'
s.exists("jjj-test/JOE.jpg")
# False
f = s.open("jjj-test/JOE.jpg", 'w')
f.write("joe test")
f.close()
s.exists("jjj-test/JOE.jpg")
# True
s.delete("jjj-test/JOE.jpg")
s.exists("jjj-test/JOE.jpg")
# False

Interacting with a Model's storage
from django.core.files.base import ContentFile
obj = MyModel()
obj.photo.save('django_test.txt', ContentFile('content'))
obj.photo.size
obj.photo.read()
obj.delete()

1 comment:

Anonymous said...

Thank you for sharing this informative blog post about Python/Django storage backend notes. It's always valuable to learn about different techniques and best practices in web development. Speaking of web development, if you're looking for a reliable hosting solution to support your Python or Django projects, I highly recommend considering Sweden VPS Hosting.