python - Blob 触发函数无法读取某些 Excel 文件

标签 python pandas azure azure-blob-storage azure-function-app

我有一些应该由 blob 触发的 azure 函数应用程序。这个想法是,每当有东西落在 blob 上时(那些应该只是 Excel 文件),该函数就会运行并进行一些处理。

def main(myblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n"
                 f"Blob Size: {myblob.length} bytes"
                 f"Returns:{myblob.read}")

    #read new data and replace nan with none values
    data = pd.read_excel(myblob)
    data = data.where(pd.notnull(data), None)

#processing

这段代码在测试期间对我有用。但是,我刚刚收到其他人编辑的文件并得到 Exception: XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\xef\xbb\xbfName,'

最后,这是为了让更多上传这些文件的人使用它,所以我必须确保它每次都有效。但是,我在这里没有看到任何模式。它适用于一个电子表格,但不适用于另一个电子表格。

最佳答案

根据pandas.read_excel官方文档,如下所示,你不能使用myblob: func.InputStream作为其参数io,因为InputStream的结构体myblobio 的类应该是带有 sas token 或 xlrd book 的 blob url。

enter image description here

enter image description here

所以我的解决方案是通过其read方法读取myblob的内容,并通过xlrd.open_workbook将其转换为xlrd Book。带有 file_contents 参数的方法。

这是我的示例代码。

import logging

import azure.functions as func

import pandas as pd
import xlrd

def main(myblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n"
                 f"Blob Size: {myblob.length} bytes")
    book = xlrd.open_workbook(file_contents=myblob.read())
    df = pd.read_excel(book)
    logging.info(f"{df}")

我的示例 xlsx 文件如下。

enter image description here

我的 local.settings.jsonfunction.jsonrequirements.txt 内容如下。

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=<your account name>;AccountKey=<your account key>;EndpointSuffix=core.windows.net"
  }
}

function.json

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "myblob",
      "type": "blobTrigger",
      "direction": "in",
      "path": "<your container name>/{name}",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

requirements.txt:仅显示我的附加软件包。

pandas==0.24.2
xlrd >= 1.0.0

它有效。结果如下:

enter image description here

关于python - Blob 触发函数无法读取某些 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515012/

相关文章:

python - 不同目录下的不同导入结果

python - 如何创建循环导入数据并按顺序保存

python + argparse - 如何从命令行获取可选参数的顺序

git - 通过deploy.cmd 文件部署azure Web 应用程序时,Grunt 安装失败

python - 对 Python 集合表示法感到困惑

python - 将 pandas DataFrame() 拆分为多列的简洁方法

python - 根据值是否存在于不同的 DataFrame 列中在 pandas DataFrame 中创建列

python - 为什么python pandas不提供linux whl文件

azure - 从 azure apim 导出的 OAS 中的安全和策略

azure - Powershell - 设置环境变量而无需关闭应用程序