You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask应用中安全选取Azure Blob Storage容器中的Blob?

问题解答

一、实现从Azure Blob Storage选择文件的功能

可以实现类似本地文件选择的体验,但流程和本地场景不同——Blob存储是云端资源,无法直接让浏览器访问容器,需要通过Flask后端作为中间层处理:

  1. 后端获取Blob列表并返回前端
    在Flask路由中连接Azure Blob Storage,拉取目标容器内的Blob列表,传递给前端页面展示。前端可通过复选框、下拉框等组件让用户选择需要的Blob。

    示例代码:

    from flask import Flask, jsonify, render_template, request
    from azure.storage.blob import BlobServiceClient
    import os
    
    app = Flask(__name__)
    
    # 初始化Blob服务客户端(安全配置见下文)
    blob_service_client = BlobServiceClient.from_connection_string(os.environ.get("AZURE_STORAGE_CONN_STR"))
    
    @app.route('/')
    def index():
        container_client = blob_service_client.get_container_client("your-container-name")
        blob_list = [blob.name for blob in container_client.list_blobs()]
        return render_template('blob_select.html', blobs=blob_list)
    
    @app.route('/process-selected', methods=['POST'])
    def process_selected():
        selected_blobs = request.json.get('selected', [])
        processed_data = []
        for blob_name in selected_blobs:
            blob_client = blob_service_client.get_blob_client("your-container-name", blob_name)
            # 示例:读取Blob内容,可根据需求改为下载到临时目录等操作
            content = blob_client.download_blob().readall().decode('utf-8')
            processed_data.append({"name": blob_name, "content": content})
        return jsonify({"status": "success", "data": processed_data})
    
  2. 前端展示与选择交互
    在前端模板(如blob_select.html)中渲染Blob列表,用户选择后提交给后端:

    <div id="blob-selector">
        {% for blob in blobs %}
            <label>
                <input type="checkbox" class="blob-option" value="{{ blob }}"> {{ blob }}
            </label><br>
        {% endfor %}
        <button onclick="submitSelection()">确认选择</button>
    </div>
    
    <script>
        function submitSelection() {
            const selected = Array.from(document.querySelectorAll('.blob-option:checked')).map(el => el.value);
            fetch('/process-selected', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({selected: selected})
            }).then(res => res.json()).then(data => {
                console.log('处理结果:', data);
                // 后续前端逻辑
            });
        }
    </script>
    

二、安全处理敏感凭证(避免暴露SAS令牌)

绝对不能将SAS令牌、存储账户连接字符串硬编码到代码中,更不能暴露给前端,推荐以下安全方案:

  • 使用Azure AD身份验证替代SAS令牌
    利用Azure AD托管标识或服务主体验证Blob服务客户端,无需依赖SAS令牌:

    from azure.identity import DefaultAzureCredential
     from azure.storage.blob import BlobServiceClient
    
     credential = DefaultAzureCredential()
     blob_service_client = BlobServiceClient(
         account_url="https://your-storage-account.blob.core.windows.net",
         credential=credential
     )
    

    部署在Azure App Service、VM等资源上时,可直接启用托管标识;本地开发时,DefaultAzureCredential会自动读取Azure CLI登录信息或本地环境变量,无需手动配置密钥。

  • 将敏感信息存入环境变量
    若必须使用连接字符串,将其存入服务器或部署平台的环境变量,Flask通过os.environ读取:

    import os
     conn_str = os.environ.get("AZURE_STORAGE_CONN_STR")
    

    切勿将环境变量内容提交到代码仓库,部署时通过平台配置面板添加。

  • 全程通过后端代理Blob操作
    所有Blob的读写、下载操作都由Flask后端完成,前端仅传递Blob名称等非敏感信息,永远不接触任何凭证。


内容的提问来源于stack exchange,提问作者surajbhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:52:50