Azure Function上传本地文件至Blob存储发布后报500错误
问题描述
通过Azure Function App实现本地Excel文件读取、Pandas数据清洗后上传至Azure Blob Storage的功能,本地离线调试时全流程逻辑运行正常,发布到Azure云端后触发 Error 500 报错。
现有实现代码
Python函数代码
#I get my files offline AISauftragID = req.params.get('ID','756382') Position = req.params.get('Position','7') location = fr'C:\Users\bb\ff\Doc\VS Code\{ID}-{Position}' #Some Cleaning using pandas #connecting to Azure blob_service_client = BlobServiceClient.from_connection_string("blablabla") # Instantiate a new ContainerClient container_client = blob_service_client.get_container_client('foldername') try: # Create new Container in the service container_client.create_container() properties = container_client.get_container_properties() except ResourceExistsError: print("Container already exists.") blob = BlobClient.from_connection_string(conn_str="blablabla", container_name="foldername", blob_name="filename") if blob.exists(): logging.info('filename.csv exists') return func.HttpResponse( "filename.csv exists", status_code=200) else: blob_client = container_client.get_blob_client("filename.csv") # upload data blob_client.upload_blob(dataframe.to_csv(index=False, encoding = "utf-8"), blob_type="BlockBlob") return func.HttpResponse( "Konto.csv exists", status_code=200)
function.json配置
{ "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" } ] }
故障原因
- 核心问题:代码中写死的
C:\Users\bb\ff\Doc\VS Code\是本地开发机的磁盘路径,发布到云端后,Azure Function运行在微软托管的远端服务器上,该服务器的文件系统里不存在这个路径,读取文件时直接抛出文件不存在异常,最终返回500错误。 - 隐性代码bug:路径拼接时使用了未定义的变量
ID,实际从请求参数里取到的ID值存在变量AISauftragID中,这段代码哪怕在本地运行,只要传入自定义ID参数就会触发NameError。
修复方案
根据实际业务场景二选一即可:
- 如果需求是调用函数时上传本地Excel文件,经清洗后存入Blob:
- 删除写死本地磁盘路径的逻辑,改为直接从HTTP请求体中接收上传的文件二进制流,Pandas支持直接从内存流读取Excel做清洗,不需要将文件存到函数运行环境的磁盘上,处理完成后直接将结果上传到Blob即可。
- 如果需要上传超过100MB的文件,需要修改函数的
host.json配置,调大HTTP请求体的大小上限,默认限制为100MB。
- 如果需求是函数自动读取个人电脑上固定路径的Excel文件做处理:
- 云端部署的函数无法主动穿透网络访问个人电脑的本地磁盘,可以选择两种方式:一是将需要处理的Excel文件提前同步到Azure Blob、OneDrive这类公网可访问的存储位置,函数运行时直接从公网地址拉取文件处理;二是不要将函数发布到云端,直接在个人电脑上运行Azure Functions运行时,本地部署执行函数。
内容的提问来源于stack exchange,提问作者Mostafa Bouzari
相关产品推荐
相关产品推荐

