user5583043
user5583043

Reputation:

Django rest framework - upload images to Azure storage

django-storages and azure-storage 0.36(newer versions give loads of errors) installed in the virtualenvironment the upload seems to be working as the API sends a response with the supposedly correct link to the image. But on the Azure storage nothing is created.

Just using the default file upload options, the file uploads work normally.

Is using the django-storages backends the way to go or am I supposed to use the Azure python sdk directly?

settings.py

INSTALLED_APPS = (
    ....
    'storages'
)

DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage'
AZURE_ACCOUNT_NAME = "myaccountname"
AZURE_ACCOUNT_KEY = "mykey"
AZURE_CONTAINER = "media"


MEDIA_ROOT = "http://mystorageaccount.blob.core.windows.net/"
MEDIA_URL = "http://mystorageaccount.blob.core.windows.net/media/"

models.py

image = models.ImageField(upload_to='images', null=True, blank=True)

With this setup it seems to be working

Upvotes: 2

Views: 1739

Answers (2)

Abdul Rafay
Abdul Rafay

Reputation: 1

if os.environ.get('ENV') in ['Dev', 'Staging', 'Production']:
    DEFAULT_FILE_STORAGE = 'backend.utils.custom_azure.AzureMediaStorage'
    STATICFILES_STORAGE = 'backend.utils.custom_azure.AzureStaticStorage'

    STATIC_LOCATION = "static"
    MEDIA_LOCATION = "data"

    AZURE_ACCOUNT_NAME = os.environ.get('AZURE_ACCOUNT_NAME', "")
    AZURE_ACCOUNT_KEY = os.environ.get('AZURE_ACCOUNT_KEY', "")
    AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net'
    AZURE_BLOB_URL = f'https://{AZURE_CUSTOM_DOMAIN}'

    AZURE_OVERWRITE_FILES = True

    STATIC_ROOT = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
    STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
    MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/'
    
    DATA_PATH = 'data'
else:
    # local environment
    SITE_URL = 'http://127.0.0.1:8050'        
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

    MEDIA_ROOT = os.path.join(BASE_DIR, 'data/')     # 'media/'
    MEDIA_URL = '/data/'    # '/media/'
    
    DATA_PATH = os.path.join(BASE_DIR, MEDIA_ROOT)

Upvotes: 0

Per Django's official documentation, they advise to install the Azure Storage SDK:

Azure Storage A custom storage system for Django using Windows Azure Storage backend.

Before you start configuration, you will need to install the Azure SDK for Python.

Install the package:

pip install azure

Add to your requirements file:

pip freeze > requirements.txt 

You should use the SDK.

Upvotes: 1

Related Questions