【问题标题】:Accessing google cloud storage from cloud function(without download)从云功能访问谷歌云存储(无需下载)
【发布时间】:2021-08-21 14:49:48
【问题描述】:

我正在运行谷歌云功能,它访问谷歌云存储桶以获取 excel 文件。我的目标是读取文件并对其进行一些计算,但是是否可以不将文件下载到 /tmp 文件夹? 我尝试过的事情:

  storage_client = storage.Client()
  file_obj = storage_client.get_bucket(‘bucketname’).get_blob('filename.xlsx')
  
  excel_file = None
  file_obj.download_to_file(excel_file)
  wb = openpyxl.load_workbook(excel_file)

起初我以为我可以获得一个文件对象,但当我阅读错误消息后,我意识到我被要求提供文件路径,所以我必须下载到 /tmp 文件夹,这是我想要的避免。

我也试过download_as_bytes(),可惜openpyxl无法读取字节。

任何帮助/提示将不胜感激:)

【问题讨论】:

  • download_as_string?
  • @guillaumeblaquiere 嗯...正如我从文档中看到的那样,它是 download_as_bytes() googleapis.dev/python/storage/latest/blobs.html 的不推荐使用的别名,但我还是尝试了,结果与 download_as_bytes: InvalidFileException: openpyxl does not support b'.xmlpk\x05\x06\x00\x00\x00\x00\x0c\x00\x0c\x00&\x03\x00\x00\x15\x97\x00\x00\x00\x00'文件格式,请查看是否可以先用Excel打开。支持的格式有:.xlsx,.xlsm,.xltx,.xltm
  • 好的,不把你的字节转换成字符串然后加载?
  • @guillaumeblaquiere 对不起......我不明白你的意思......我在做 download_as_string 或 download_as_bytes 时没有进行任何转换
  • 你检查过这个community answer吗?它解释说 openpyxl 需要一个路径或接受一个类似文件的对象,所以如果你有一个字节,你可以按照你的案例的答案中的示例进行操作。你认为这对你有用吗?

标签: google-cloud-platform google-cloud-functions


【解决方案1】:

正如您在Community Answer 中看到的:

openpyxl.load_workbook 的文档中写道:

#:param filename: the path to open or a file-like object

所以如果你有字节作为输入,你可以组装一个“原型对象”来满足openpyxl.load_workbook的参数要求,它会起作用,就像下面的例子:

from io import BytesIO
...
excel_file = None
file_obj.download_as_bytes(excel_file)
wb = load_workbook(filename=BytesIO(excel_file.read()))

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2021-08-20
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多