【问题标题】:Read in azure blob using python使用 python 在 azure blob 中读取
【发布时间】:2020-11-04 13:58:25
【问题描述】:

我想将存储在 Azure blob 存储中的 excel 文件读取到 python 数据框。我会使用什么方法?

【问题讨论】:

标签: python azure-functions azure-blob-storage azure-blob-trigger


【解决方案1】:

pandas包中有一个名为read_excel的函数,可以将在线excel文件的url传给函数,获取excel表的dataframe,如下图。

所以你只需要生成一个带有 sas 令牌的 excel blob 的 url,然后将它传递给函数。

这是我的示例代码。注意:需要安装Python包azure-storagepandasxlrd

# Generate a url of excel blob with sas token
from azure.storage.blob.baseblobservice import BaseBlobService
from azure.storage.blob import BlobPermissions
from datetime import datetime, timedelta

account_name = '<your storage account name>'
account_key = '<your storage key>'
container_name = '<your container name>'
blob_name = '<your excel blob>'

blob_service = BaseBlobService(
    account_name=account_name,
    account_key=account_key
)

sas_token = blob_service.generate_blob_shared_access_signature(container_name, blob_name, permission=BlobPermissions.READ, expiry=datetime.utcnow() + timedelta(hours=1))
blob_url_with_sas = blob_service.make_blob_url(container_name, blob_name, sas_token=sas_token)

# pass the blob url with sas to function `read_excel`
import pandas as pd
df = pd.read_excel(blob_url_with_sas)
print(df)

我使用我的示例 excel 文件来测试下面的代码,它工作正常。

图 1. 我在 Azure Blob 存储的 test 容器中的示例 excel 文件 testing.xlsx

图2.我的示例excel文件testing.xlsx的内容

图 3. 我的示例 Python 代码读取 excel blob 的结果

【讨论】:

  • 这会在尝试从嵌套文件中获取 blob 时出现 http 400 错误(例如,它适用于文件夹/文件,但不适用于文件夹/文件夹/文件),你知道如何解决这个问题吗?
  • @dragonfromdreamsd 请创建一个新的 SO 线程来发布您的问题的详细信息,然后我会帮助您。
  • 没有这样的模块:from azure.storage.blob.baseblobservice import BaseBlobService
  • @mas 请检查 Azure Storage SDK 的版本是旧 v2 还是新 v12。
  • 感谢彼得,这篇文章中的第二个解决方案对我有用。 link
猜你喜欢
  • 2018-07-30
  • 2021-08-30
  • 2021-12-18
  • 2021-06-01
  • 2021-10-05
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多