使用Azure Storage SDK与Django(并彻底删除对django存储的依赖) [英] Using Azure Storage SDK with Django (and removing dependency on django-storages entirely)

查看:174
本文介绍了使用Azure Storage SDK与Django(并彻底删除对django存储的依赖)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有直接使用 azure-storage 的提示与Django?我问,因为目前我正在为我的Django应用(使用Ubuntu操作系统托管在Azure VM上)设置Azure云存储,而 django-storages 似乎没有与Azure Storage SDK正确连接(已知问题:见这里)。鉴于我的Django版本是< 1.6.2。



因此,我需要直接使用Azure存储与Django。有人设定了吗?我需要在云端存储上保存图像 mp3s






目前,在我的models.py中,我有:

  def upload_to_location(instance,filename):
try
块= filename.split('。')
ext = blocks [-1]
filename =%s。%s%(uuid.uuid4(),ext)
instance.title = blocks [0]
return os.path.join('uploads /',filename)
除了例外为e:
print'%s(%s) '%(e.message,type(e))
返回0

类照片(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)

然后 django-storages boto 照顾其余的。但是,当我使用Azure Cloud Storage挂起django存储时,我收到以下错误:

 异常值:
'module'对象没有属性'WindowsAzureMissingResourceError'

异常位置:
/home/mhb11/.virtualenvs/myvirtualenv/local/lib/python2.7/site-packages/storages/后端/ azure_storage.py存在,第46行

代码的相关代码段是:存在(self,name):
try:
self.connection.get_blob_properties(


$ b $ self.azure_container,name)
除了azure.WindowsAzureMissingResourceError:
return False
else:
返回True

看起来与Azure容器的连接失败。在我的settings.py中,我有:

  DEFAULT_FILE_STORAGE ='storages.backends.azure_storage.AzureStorage'
AZURE_ACCOUNT_NAME = 'photoatabasestorage'
AZURE_ACCOUNT_KEY ='something'
AZURE_CONTAINER ='somecontainer'

如前所述,我需要一个完全绕过django存储的解决方案,只需依靠Azure Storage SDK完成工作。



注意:问我

解决方案

我们可以直接使用 Azure-Storage python SDK ,就像在常见的python应用程序中使用sdk一样。您可以参考官方指南开始使用。



以下是Django应用中的测试代码片段:

  def putfiles(request):
blob_service = BlobService(account_name = accountName,account_key = accountKey)
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__ file__) )
try:
blob_service.put_block_blob_from_path(
'mycontainer',
'123.jpg',
path.join(path.join(PROJECT_ROOT,'uploads '),'123.jpg'),
x_ms_blob_content_type ='image / jpg'

result = True
除了:
print(sys.exc_info() [1])$ ​​b $ b result = False
return HttpResponse(result)


def listfiles(request):
blob_service = BlobService(account_name = accountName, account_key = accountKey)
blobs = []
result = []
标记=无
,而True:
批次= blob_service.list_blobs('mycontainer',marker =标记)
blobs.extend(批处理)
如果不是batch.next_marker:
break
marker = batch.next_marker
用于blob中的blob:
result.extend([{'name':blob.name}])
return HttpResponse(json.dumps(result))


Does anyone have any tips on using azure-storage directly with Django? I ask because currently I'm trying to set up Azure Cloud Storage for my Django app (hosted on Azure VM with Ubuntu OS), and django-storages doesn't seem to be interfacing with Azure Storage SDK correctly (known issue: see here). The fix listed there won't work for me given my Django version is < 1.6.2.

Thus I'll need to use Azure-storage directly with Django. Has anyone set that up before? I need to save images and mp3s on the Cloud Storage.


Currently, in my models.py, I have:

def upload_to_location(instance, filename):
    try:
        blocks = filename.split('.') 
        ext = blocks[-1]
        filename = "%s.%s" % (uuid.uuid4(), ext)
        instance.title = blocks[0]
        return os.path.join('uploads/', filename)
    except Exception as e:
        print '%s (%s)' % (e.message, type(e))
        return 0

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 )

And then django-storages and boto take care of the rest. However, when I hook django-storages up with Azure Cloud Storage, I get the following error:

Exception Value:      
'module' object has no attribute 'WindowsAzureMissingResourceError'

Exception Location:     
/home/mhb11/.virtualenvs/myvirtualenv/local/lib/python2.7/site-packages/storages/backends/azure_storage.py in exists, line 46

And the relevant snippet of the code is:

def exists(self, name):
    try:
        self.connection.get_blob_properties(
            self.azure_container, name)
    except azure.WindowsAzureMissingResourceError:
        return False
    else:
        return True

Seems that the connection to the Azure container is failing. In my settings.py, I have:

    DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage'
    AZURE_ACCOUNT_NAME = 'photodatabasestorage'
    AZURE_ACCOUNT_KEY = 'something'
    AZURE_CONTAINER = 'somecontainer'

As described earlier, I need a solution that bypasses django-storages entirely, and just relies on Azure Storage SDK to get the job done.

Note: ask me for more information in case you need it.

解决方案

We can directly use Azure-Storage python SDK in the Django apps just like using the sdk in common python applications. You can refer to official guide for getting started.

Here is the test code snippet in the Django app:

def putfiles(request):
blob_service = BlobService(account_name=accountName, account_key=accountKey)
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
try:
    blob_service.put_block_blob_from_path(
            'mycontainer',
            '123.jpg',
            path.join(path.join(PROJECT_ROOT,'uploads'),'123.jpg'),
            x_ms_blob_content_type='image/jpg'
    )
    result = True
except:
    print(sys.exc_info()[1])
    result = False
return HttpResponse(result)


def listfiles(request):
    blob_service = BlobService(account_name=accountName, account_key=accountKey)
    blobs = []
    result = []
    marker = None
    while True:
        batch = blob_service.list_blobs('mycontainer', marker=marker)
        blobs.extend(batch)
        if not batch.next_marker:
            break
        marker = batch.next_marker
    for blob in blobs:
        result.extend([{'name':blob.name}])
    return HttpResponse(json.dumps(result))

这篇关于使用Azure Storage SDK与Django(并彻底删除对django存储的依赖)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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