关于python 2.7:Django返回blob形式的azure-storage作为可下载文件

Django return blob form azure-storage as downloadable file

我是天蓝色存储和Django的新手
我的开发环境软件配置为asdjango 1.10,python 2.7.6,azure-storage-blob 0.37。 我正在使用django应用程序作为web服务api,并且前端是使用angular-2和HTML构建的

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

我保存文件的azure blob容器仅具有私有访问权限。我能够成功上传文件。

问题是在下载文件时-
我正在努力实现的是-

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

    block_blob_service._get_blob(容器,blob_name)

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

  • 您能建议我解决这个问题还是更好的方法。

    提前致谢。


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

    请按照本教程在项目中配置Azure存储帐户。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    # Replace <...> appropriately with your information

    # AzureStorage Settings
    AZURE_STORAGE_ACCOUNT =""
    AZURE_STORAGE_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>/'

    您可以在此处和此处获得更多详细信息。

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

    根据您的需要,只需使用Azure存储Python SDK。

    请按照以下步骤操作。

    步骤1:将要下载的Blob名称绑定到hyperlink,并在用户单击时将blob name作为参数传递给后端。

    步骤2:获取Blob网址。

    1
    2
    3
    4
    5
    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

    步骤3:通过StreamingHttpResponse在浏览器中下载文件。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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.将文件从远程URL流到Django视图响应

    2.如何在Django中将文件流式传输到客户端

    希望对您有帮助。