如何使用Azure的BlobService对象上传与Django模型关联的文件

时间:2015-12-15 15:52:43

标签: python django azure azure-cloud-services

我有一个Django应用程序,用户可以上传照片和说明。这是一个促进用户行为的典型模型:

class Photo(models.Model):
    description = models.TextField(validators=[MaxLengthValidator(500)])
    submitted_on = models.DateTimeField(auto_now_add=True)
    image_file = models.ImageField(upload_to=upload_to_location, null=True, blank=True )

请注意 image_file 属性具有upload_to参数,该参数由 image_file 的上传目录和文件名提供。 upload_to_location方法处理这个问题;假设它正常工作。

现在我想将每个图像上传到Azure云端存储。这样做的python片段是explained here。使用它,我尝试编写自己的自定义存储,将图像保存到Azure。虽然这很麻烦,我需要帮助清理它。这就是我所做的:

models.py 中的image_file属性更改为:

image_file = models.ImageField("Tasveer dalo:",upload_to=upload_to_location, storage=OverwriteStorage(), null=True, blank=True )

然后在我的app文件夹中创建了一个单独的 storage.py ,其中包含:

from django.conf import settings
from django.core.files.storage import Storage
from azure.storage.blob import BlobService

class OverwriteStorage(Storage):
    def __init__(self,option=None):
        if not option:
            pass
    def _save(name,content):
        blob_service = BlobService(account_name='accname', account_key='key')
        PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
        try:
            blob_service.put_block_blob_from_path(
                    'containername',
                    name,
                    path.join(path.join(PROJECT_ROOT,'uploads'),name),
                    x_ms_blob_content_type='image/jpg'
            )
            return name
        except:
            print(sys.exc_info()[1])
            return 0
    def get_available_name(self,name):
        return name

此设置不起作用,并返回错误:_save() takes exactly 2 arguments (3 given). Exception Location: /home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/core/files/storage.py in save, line 48

如何使这项工作?有没有人以这种方式使用Azure-Storage python SDK和他们的Django项目?请指教。

注意:最初,我使用的是django-storages库,它模糊了我的存储详细信息,将所有内容减少到只需要在settings.py中输入的一些配置。但是现在,我需要从等式中删除django-storages,并仅将Azure-Storage python SDK用于此目的。

注意:如果需要,请询问更多信息

1 个答案:

答案 0 :(得分:0)

根据您的错误消息,您错过了函数_save()中的参数,该参数应以_save(self,name,content)等格式填写。

此外,您似乎希望将图像直接放到从客户端表单上载的Azure存储中。如果是这样,我在github中找到了一个repo,它为Django模型构建了一个自定义的azure存储类。我们可以利用它来修改您的应用程序。有关详细信息,请参阅https://github.com/Rediker-Software/django-azure-storage/blob/master/azure_storage/storage.py

这是我的代码片段, 的 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'

class OverwriteStorage(Storage):
    def __init__(self,option=None):
        if not option:
            pass
    def _save(self,name,content):
        blob_service = BlobService(account_name=accountName, account_key=accountKey)
        import mimetypes

        content.open()

        content_type = None

        if hasattr(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
    def get_available_name(self,name):
        return name

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

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