Skip to content Skip to sidebar Skip to footer

How To Use Azure's Blobservice Object To Upload A File Associated To A Django Model

I have a Django app where users upload photos and descriptions. Here's a typical model which facilitates that user behavior: class Photo(models.Model): description = models.Tex

Solution 1:

According your error message, you missed parameter in function _save() which should be complete in the format like _save(self,name,content).

And additionally, it seems that you want put the images directly to Azure Storage which are uploaded from client forms. If so, I found a repo in github which builds a custom azure storage class for Django models. We can get leverage it to modify your application. For more details, refer to https://github.com/Rediker-Software/django-azure-storage/blob/master/azure_storage/storage.py

And here are my code snippets, models.py:

from django.db import models
from django.conf import settings
from django.core.files.storage import Storage
from azure.storage.blob import BlobService
accountName = 'accountName'
accountKey = 'accountKey'classOverwriteStorage(Storage):
    def__init__(self,option=None):
        ifnot option:
            passdef_save(self,name,content):
        blob_service = BlobService(account_name=accountName, account_key=accountKey)
        import mimetypes

        content.open()

        content_type = Noneifhasattr(content.file, 'content_type'):
            content_type = content.file.content_type
        else:
            content_type = mimetypes.guess_type(name)[0]

        content_str = content.read()


        blob_service.put_blob(
            'mycontainer',
            name,
            content_str,
            x_ms_blob_type='BlockBlob',
            x_ms_blob_content_type=content_type
        )

        content.close()

        return name
    defget_available_name(self,name):
        return name

defupload_path(instance, filename):
    return'uploads-from-custom-storage-{}'.format(filename)

classPhoto(models.Model):
   image_file = models.ImageField(upload_to=upload_path, storage=OverwriteStorage(), null=True, blank=True )

Post a Comment for "How To Use Azure's Blobservice Object To Upload A File Associated To A Django Model"