如何使用Azure的BlobService对象上载与Django模型关联的文件 [英] How to use Azure's BlobService object to upload a file associated to a Django model

查看:90
本文介绍了如何使用Azure的BlobService对象上载与Django模型关联的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.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方法可以解决这个问题.假设它正常工作.

Notice the image_file attribute has upload_to argument, which is fed the upload directory and file name of the image_file. The upload_to_location method takes care of that; assume it works correctly.

现在,我想将每个映像上传到Azure云存储.做到这一点的python代码段说明这里.使用这种方法,我尝试编写自己的自定义存储,将图像保存到Azure.虽然这是越野车,但我需要帮助来清理它.这是我所做的:

Now I want to upload each image to Azure Cloud Storage. The python snippet to do that is explained here. Using that, I tried to write my own custom storage that saves images to Azure. It's buggy though, and I need help in cleaning it up. Here's what I've done:

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

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

然后在我的应用文件夹中创建一个单独的 storage.py ,该文件夹具有:

And then created a separate storage.py in my app folder that has:

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

This set up doesn't work, and returns the error: _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

我如何进行这项工作?有没有人以这种方式在其Django项目中使用Azure-Storage python SDK?请告知.

How do I make this work? Has anyone used Azure-Storage python SDK with their Django projects in this way? Please advise.

注意:最初,我使用的是django-storages库,该库混淆了我的存储详细信息,将所有内容减少为仅一些要在settings.py中输入的配置.但是现在,我需要从等式中删除django-storages,并且仅使用为此,请使用Azure存储python SDK .

Note: Originally, I was using the django-storages library, which obfuscated storage details from me, reducing everything to just some configuration to be entered in settings.py. But now, I need to remove django-storages from the equation, and solely use the Azure-Storage python SDK for the purpose.

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

推荐答案

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

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

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

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

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

这篇关于如何使用Azure的BlobService对象上载与Django模型关联的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆