有没有人有任何关于直接使用Django azure-storage的提示?我问,因为目前我正在尝试为我的Django应用程序设置Azure云存储(使用Ubuntu OS托管在Azure VM上),django-storages
似乎无法正确连接Azure Storage SDK (已知问题:see here)。鉴于我的Django版本是<而且那里列出的修复程序对我来说不起作用。 1.6.2。
因此,我需要直接使用Azure存储与Django。有人有过这样的话吗?我需要在云存储上保存图像和 mp3 。
目前,在我的models.py中,我有:
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 )
然后django-storages
和boto
负责其余的工作。但是,当我使用Azure云存储挂起django-storage时,我收到以下错误:
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
代码的相关片段是:
def exists(self, name):
try:
self.connection.get_blob_properties(
self.azure_container, name)
except azure.WindowsAzureMissingResourceError:
return False
else:
return True
似乎与Azure容器的连接失败。在我的settings.py中,我有:
DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage'
AZURE_ACCOUNT_NAME = 'photodatabasestorage'
AZURE_ACCOUNT_KEY = 'something'
AZURE_CONTAINER = 'somecontainer'
如前所述,我需要一个完全绕过django-storage的解决方案,只需依靠Azure Storage SDK即可完成工作。
注意:如果您需要,请向我询问更多信息。
答案 0 :(得分:2)
我们可以直接在Django应用程序中使用Azure-Storage python SDK,就像在常见的python应用程序中使用sdk一样。您可以参考official guide开始使用。
以下是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
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))