将熊猫数据帧作为 xlsx 文件写入 Azure Blob 存储,而不创建本地文件



我有以下使用本地文件的解决方案,但我想跳过它。有没有可能?

blob_service_client = BlobServiceClient(account_url = url, credential = token)
write_blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
filename = "example.xlsx"
df.to_excel(filename ,index = False)
with open(filename, "rb") as df:
write_blob_client.upload_blob(df, overwrite = True)

而不是我尝试过的最后三行

teststream = BytesIO(df.to_records(index = False).tostring())
write_blob_client.upload_blob(teststream, overwrite = True)

这会将 excel 文件写入 blob 存储,但在尝试打开它时,我收到一条错误消息,指出文件扩展名与文件格式不匹配。

您必须从 BytesIO 对象中获取值。以下代码对我有用。

writer = io.BytesIO()
df.to_excel(writer)
blob_client.upload_blob(writer.getvalue(), overwrite = True)

当然,您不需要创建本地文件。

您只需要将流放入upload_blob即可。您似乎正在使用 offcial 提供的示例代码。你不需要使用open(filename, "rb") as df,只需转换为流就可以了。

这是我的代码:

import logging
import azure.functions as func
import os, uuid, io
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
connect_str = os.getenv('str')
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = "video"
container_client = blob_service_client.get_container_client(container_name)
filename = "test.xlsx"
blob_client = blob_service_client.get_blob_client(container_name, filename)
teststream = io.BytesIO(req.get_body())
blob_client.upload_blob(teststream, overwrite = True)
name = req.params.get('name')
return func.HttpResponse("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")

上面的代码将请求正文从字节转换为流,并上传到 Azure Blob 存储。

让我知道你是否可以解决,有任何疑问请告诉我.:)

相关内容

最新更新