Python Azure Blob触发函数文件名打印异常问题排查
Azure Blob触发函数中输入绑定Blob名称显示异常问题
问题场景
通过Blob触发事件运行Python Azure函数,容器samples-workitems中已存在base.csv文件。当容器接收新文件new.csv时,函数通过InputStream读取同一容器内的base.csv和new.csv。
函数代码
import logging import pandas as pd from io import BytesIO import azure.functions as func def main(myblob: func.InputStream, base: func.InputStream): logging.info(f"Python blob trigger function processed blob \n" f"Name: {myblob.name}\n" f"Blob Size: {myblob.length} bytes") logging.info(f"Base file info \n" f"Name: {base.name}\n" f"Blob Size: {base.length} bytes") df_base = pd.read_csv(BytesIO(base.read())) df_new = pd.read_csv(BytesIO(myblob.read())) print(df_new.head()) print("printing base dataframe") print(df_base.head())
运行输出
Python blob trigger function processed blob Name: samples-workitems/new.csv Blob Size: None bytes Base file info Name: samples-workitems/new.csv Blob Size: None bytes first 5 rows of df_new (cannot show data here) printing base dataframe first 5 rows of df_base (cannot show data here)
配置文件(function.json)
{ "scriptFile": "__init__.py", "bindings": [ { "name": "myblob", "type": "blobTrigger", "direction": "in", "path": "samples-workitems/{name}", "connection": "my_storage" }, { "type": "blob", "name": "base", "path": "samples-workitems/base.csv", "connection": "my_storage", "direction": "in" } ] }
异常现象
两个文件的内容能正常打印,但myblob.name和base.name均显示为samples-workitems/new.csv,不符合预期——base.name应该显示samples-workitems/base.csv。
问题原因
这是Azure Functions Python运行时的已知行为:当Blob触发器绑定使用了占位符(如{name}),同一函数内其他Blob输入绑定的name属性会被触发器的占位符值覆盖,导致元数据显示错误,但实际读取的Blob内容是正确的。
解决方法
方法1:手动指定固定文件名
由于base.csv的路径是固定的,可直接在代码中使用硬编码的文件名,无需依赖base.name:
# 修改日志输出部分 logging.info(f"Base file info \n" f"Name: samples-workitems/base.csv\n" f"Blob Size: {base.length} bytes")
方法2:从Blob URI解析正确名称
通过base.uri属性解析出真实的Blob路径:
import logging import pandas as pd from io import BytesIO import azure.functions as func from urllib.parse import urlparse def main(myblob: func.InputStream, base: func.InputStream): logging.info(f"Python blob trigger function processed blob \n" f"Name: {myblob.name}\n" f"Blob Size: {myblob.length} bytes") # 解析base文件的正确名称 base_uri = urlparse(base.uri) base_file_name = base_uri.path.lstrip('/') logging.info(f"Base file info \n" f"Name: {base_file_name}\n" f"Blob Size: {base.length} bytes") df_base = pd.read_csv(BytesIO(base.read())) df_new = pd.read_csv(BytesIO(myblob.read())) print(df_new.head()) print("printing base dataframe") print(df_base.head())
方法3:修改触发器占位符名称
将触发器绑定中的占位符{name}改为其他名称(如{blobname}),避免名称冲突:
{ "scriptFile": "__init__.py", "bindings": [ { "name": "myblob", "type": "blobTrigger", "direction": "in", "path": "samples-workitems/{blobname}", "connection": "my_storage" }, { "type": "blob", "name": "base", "path": "samples-workitems/base.csv", "connection": "my_storage", "direction": "in" } ] }
内容的提问来源于stack exchange,提问作者Shaida Muhammad
相关产品推荐
相关产品推荐

