我有一些应该由 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
的结构体myblob
和 io
的类应该是带有 sas token 或 xlrd book 的 blob url。
所以我的解决方案是通过其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
文件如下。
我的 local.settings.json
、function.json
和 requirements.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
它有效。结果如下:
关于python - Blob 触发函数无法读取某些 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515012/