Django Azure upload file to blob storage

前端 未结 2 2377
野的像风
野的像风 2021-01-06 22:00

I\'ve got an application that needs to upload a file to an Azure Blob Storage container. I\'ve been trying for a very long time and followed every tutorial to no avail.

2条回答
  •  無奈伤痛
    2021-01-06 22:25

    Figured out the problem. I followed a tutorial for Amazon S3 and then applied the exact same principals to the Azure scenario. After all, I'm sure the developer of this class wanted to keep everything uniform.

    mysite/custom_azure.py <-- just put it in the same folder as your settings.py file

    from storages.backends.azure_storage import AzureStorage
    
    class AzureMediaStorage(AzureStorage):
        location = 'media'
        file_overwrite = False
    

    mysite/settings.py

    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, '/static'),
    ]
    
    AZURE_ACCOUNT_NAME = ''
    AZURE_ACCOUNT_KEY = ''
    AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net'
    AZURE_LOCATION = ''
    AZURE_CONTAINER = ''
    
    STATIC_LOCATION = 'static'
    STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
    
    STATICFILES_STORAGE = 'storages.backends.azure_storage.AzureStorage'
    DEFAULT_FILE_STORAGE = 'mysite.custom_azure.AzureMediaStorage'
    

    Also, note that if you have the following in your mysite/urls.py from some other tutorial or something:

    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    you need to remove the MEDIA line:

    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    

    from the model, remove any reference to 'storage' and just leave the 'upload_to' option like this:

    thumbnail = models.ImageField(default='default.jpg', upload_to='video_thumbs')
    

    it all just worked.

    don't for get to do the following to check yourself:

    python3 manage.py collectstatic
    

    hope this helps other people!!!

提交回复
热议问题