【问题标题】:How to use Azure's BlobService object to upload a file associated to a Django model如何使用 Azure 的 BlobService 对象上传与 Django 模型关联的文件
【发布时间】:2015-12-16 14:17:11
【问题描述】:

我有一个 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 sn-p 是 explained here。使用它,我尝试编写自己的自定义存储,将图像保存到 Azure。不过它有问题,我需要帮助来清理它。这是我所做的:

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

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

然后在我的应用文件夹中创建了一个单独的 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 来达到目的。

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

【问题讨论】:

    标签: python django azure azure-cloud-services


    【解决方案1】:

    根据您的错误消息,您错过了函数_save() 中的参数,该参数应以_save(self,name,content) 之类的格式完成。

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

    这是我的代码 sn-ps, 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 )
    

    【讨论】:

    • Gary,当我尝试这个时发生了一些奇怪的事情。我的代码顺利通过_save,一直到return namecontent.closed() 之后的行)。但在那之后它会在某个地方弹出一个错误,给我NotImplementedError at / No exception supplied. Exception Location: /home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/core/files/storage.py in url, line 121。一个对象确实出现在 Azure blob 中,但它没有加载并且出现该错误。 content_type 会有问题吗?如何调试这个?
    • 我意识到这个问题与上传文件是分开的——它与在 Django 中设置 imagefield 属性的 url 有关。我在这里将其设置为不同的 SO 帖子:stackoverflow.com/questions/34322310/…
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多