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

从ADL Gen 2异步下载Blob时出现未关闭客户端会话警告

解决Azure函数中"Unclosed client session"警告问题

问题场景

我有一个读取并处理Blob的Azure函数应用,运行时一直弹出“Unclosed client session”警告。调用链是主函数通过await调用getBlob,getBlob再通过await调用read_blob_content完成Blob下载。在read_blob_content里用了async with aiohttp.ClientSession()创建会话,试过添加/移除await session.close()、调整缩进,都没解决问题。

相关代码

主函数代码

import logging
from ..shared import blobOpsAIO
import azure.functions as func
import pandas as pd
from ..shared import invOps
import sys, os

async def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        req_body = req.get_json()
        file_name_path = req_body.get("file_name_path", "")
        file_name = req_body.get("file_name", "")
        account_id = req_body.get("account_id", "")

        inv = await getBlob(file_name_path, file_name, container_name=account_id)

        # process inv

getBlob函数代码

async def getBlob(blobPathName, LOCALFILENAME, dtype_param = None, container_name = 'somevalue', blob_type = 'csv', encoding='UTF-8', skiprows=0, header=0, sep=','):
        df = pd.DataFrame()
        # some validations   
        df = await read_blob_content(connection_string, container_name, blobPathName, blob_type, LOCALFILENAME, dtype_param, encoding, skiprows, header, sep)
        # do something with df
        return df

read_blob_content函数代码

async def read_blob_content(connection_string, container_name, blob_name, blob_type, LOCALFILENAME, dtype_param, encoding, skiprows=0, header=0, sep=","):
                async with aiohttp.ClientSession() as session:
                    blob_client = BlobClient.from_connection_string(
                        conn_str=connection_string,
                        container_name=container_name,
                        blob_name=blob_name
                    )
                    print(f'Going to fetch blobPathName: {blob_name}')
                    blob_data = await blob_client.download_blob()
                    async with aiofiles.open(LOCALFILENAME, "wb") as my_blob:
                        data = await blob_data.readall()
                        await my_blob.write(data)
                    await session.close()    # also tried placing this line one level up in the identation 
                success = True
            
            # open the file using pandas and write to df
        return df
    except Exception as e:
        print(str(e))
        raise e

问题根源与修复方案

核心问题是你创建的aiohttp.ClientSession完全没有被使用,属于冗余代码,这个无意义的会话没有被正确回收,才触发了警告。

修复步骤

  1. 移除无用的aiohttp.ClientSession代码块
    你的BlobClient是通过Azure SDK直接创建的,本身已经封装了HTTP会话管理,完全不需要额外的aiohttp会话。直接删掉整个async with aiohttp.ClientSession() as session:代码块,把里面的逻辑移出来即可。

  2. 修正代码结构
    移除冗余会话后,就不会再产生未关闭的会话对象,警告自然消失。

修复后的read_blob_content代码示例

async def read_blob_content(connection_string, container_name, blob_name, blob_type, LOCALFILENAME, dtype_param, encoding, skiprows=0, header=0, sep=","):
    try:
        blob_client = BlobClient.from_connection_string(
            conn_str=connection_string,
            container_name=container_name,
            blob_name=blob_name
        )
        print(f'Going to fetch blobPathName: {blob_name}')
        blob_data = await blob_client.download_blob()
        async with aiofiles.open(LOCALFILENAME, "wb") as my_blob:
            data = await blob_data.readall()
            await my_blob.write(data)
        success = True

        # 保留原有pandas处理逻辑
        df = pd.read_csv(LOCALFILENAME, dtype=dtype_param, encoding=encoding, skiprows=skiprows, header=header, sep=sep)
        return df
    except Exception as e:
        print(str(e))
        raise e

额外提示

如果后续确实需要使用aiohttp发起HTTP请求,只需依赖async with上下文管理器即可——它会自动帮你关闭会话,不要手动调用session.close(),否则反而可能引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:45:10