【问题标题】:Django return blob form azure-storage as downloadable fileDjango 将 blob 形式返回为 azure-storage 作为可下载文件
【发布时间】:2017-10-11 07:27:39
【问题描述】:

我是 azure-storage 和 django 的新手 我的开发环境软件配置是 as-django 1.10、python 2.7.6、azure-storage-blob 0.37。我使用 django 应用程序作为 webservice api,前端是使用 angular-2 和 HTML 构建的

我正在使用 azure blob 存储来存储任何类型的文件。

我保存文件的天蓝色 blob 容器只有私人访问权限。我能够成功上传文件。

问题是在下载文件时- 我想要实现的是 -

  1. 当有人点击页面请求上的超链接时,将转到带有 blob 名称的 django 视图。然后我可以使用容器名称和 blob 名称获取 blob

    block_blob_service._get_blob(container,blob_name)

  2. 我想在 django 响应中将该 blob 作为可下载文件返回。

您能否建议我可以实现这一目标的解决方案或更好的方法。

提前致谢。

【问题讨论】:

    标签: django python-2.7 azure azure-blob-storage


    【解决方案1】:

    我建议你在 Django 中使用Azure Storage System

    请按照此tutorial 在您的项目中配置您的 Azure 存储帐户。

    # Replace <...> appropriately with your information
    
    # AzureStorage Settings
    AZURE_STORAGE_ACCOUNT = "<account_name>"
    AZURE_STORAGE_KEY = "<account_key>"
    AZURE_STORAGE_CONTAINER = "<default_storage_container>" # statics will use this container
    
    # Static Settings
    STATICFILES_STORAGE = "<my_project>.storage.AzureStorage"
    STATIC_URL = "http://<storage account>.blob.core.windows.net/<default_storage_container>/"
    
    # Media Settings
    MEDIA_URL = 'http://storage.pepperdeck.com/<media_container>/'
    

    您可以通过herehere 获取更多详细信息。


    更新答案: 实际上,我昨天提供的 Django-Azure-Storage 本质上是对 azure storage SDK 的适配器调用。您在回复中提到的media container实际上是不需要配置的,因为您只是指Azure Storage。

    根据你的需要,使用 Azure Storage Python SDK 即可。

    请按照以下步骤操作。

    Step1:将要下载的blob名称绑定到hyperlink,并将blob name作为参数传递给后端用户点击。

    Step2:获取 blob url。

    def GetBlobUrl():
        blobService = BlockBlobService(account_name=accountName, account_key=accountKey)
        sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1))
        # print url
        return 'https://' + <your_account_name> + '.blob.core.windows.net/' + <your_container_name> + '/<your_blob_name>?' + sas_token
    

    Step3:在浏览器中通过StreamingHttpResponse下载文件。

    import requests
    from django.http import StreamingHttpResponse
    
    def stream_file(request, *args, **kwargs):
        file_url = "<blob url you get in the Previous step >"
    
        r = requests.get(file_url, stream=True)
    
        resp = StreamingHttpResponse(streaming_content=r)
        resp['Content-Disposition'] = 'attachment; filename="<your blob name>"'
    

    您也可以参考以下主题:

    1.Stream file from remote url to Django view response

    2.how to stream file to client in django

    希望对你有帮助。

    【讨论】:

    • MEDIA_URL = 'storage.pepperdeck.com/<media_container>' 这里面有什么 media_conatiner?
    • 您能否详细介绍一下 MEDIA_URL 和 MEDIA_ROOT 以及需要哪些设置 urls.py
    • @sachin27 当然。请给我一些时间来更新我的答案。
    • @sachin27 嗨,请查看我的更新答案。如有任何疑问,请随时告诉我。
    • @sachin27 查了很多文档,没有找到关于私有访问和匿名访问性能的官方描述。根据我的经验,这两种访问方式都是 REST API,应该推荐私有访问,因为它是安全的。
    【解决方案2】:

    我可以将我的几分钱添加到@Jay Gong 的答案中。

    第一个答案

    这是azure-storage-blob v12的解决方案。

    azure-storage-blob==12.8.1
    
    import requests
    
    from django.http import StreamingHttpResponse
    
    from app_module.settings import AZURE_ACCOUNT_KEY # blob storage access key
    from app_module.settings import AZURE_ACCOUNT_NAME # blob storage name
    from app_module.settings import AZURE_CONTAINER # name of container
    from app_module.settings import AZURE_ENDPOINT_SUFFIX # "core.windows.net"
    
    
    def get_blob_url(file_path):
        sas_token = generate_account_sas(
            account_name=AZURE_ACCOUNT_NAME,
            account_key=AZURE_ACCOUNT_KEY,
            resource_types=ResourceTypes(service=True, container=True, object=True),
            permission=AccountSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1)
        )
    
        return f'https://{AZURE_ACCOUNT_NAME}.blob.{AZURE_ENDPOINT_SUFFIX}/{AZURE_CONTAINER}/{file_path}?{sas_token}'
    
    
    def download(request):
        file_name = 'example.png'
        file_location_in_blob = '/path/to/file/inside/blob/storage/' + file_name
    
        url = get_blob_url(file_location_in_blob)
    
        request = requests.get(url, stream=True)
        response = StreamingHttpResponse(streaming_content=request)
    
        response['Content-Disposition'] = f'attachment; filename={file_name}'
    
        return response
    

    第二个答案

    这是azure-storage-blob v2 的解决方案。它更加优雅,因为您不必构建流式响应。

    azure-storage-blob==2.1.0 
    
    from django.http import HttpResponse
    
    def download(request):
        object = Model.objects.last()
        
        # file is FileField or its deriveritives ImageField
        response = HttpResponse(object.file) 
        response['Content-Disposition'] = f'attachment; filename={file_name}'
    
        return response
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2021-08-11
      • 1970-01-01
      • 2018-10-04
      • 2022-11-02
      • 2017-08-02
      • 2017-08-20
      相关资源
      最近更新 更多