python Firebase Cloud Storage - 上传文件而不将其保存在本地

问题描述 投票:0回答:2

我想将 zip 文件上传到 Firebase Cloud Storage,但我想避免将其保存在本地。相反,我想将其存储在内存中(使用

BytesIO
),然后直接上传。 可以吗?

python zip google-cloud-storage firebase-admin
2个回答
0
投票

理论上,这应该可以从

BytesIO
写入存储,而无需在本地写入文件。

Blob
类中有一个方法称为
upload_from_string
reference)。该方法接受
bytes
并且也可以添加内容类型。前任。我能够运行类似的东西:

    # create simplest BytesIO object
    b = io.BytesIO(b'hello')
    # create storage client
    storage_client = storage.Client()
    # create test bucket
    bucket = storage_client.bucket("vittoh-test-bytesio")
    # create test blob
    blob = bucket.blob("vitooh-test-blob")
    # upload with type zip
    blob.upload_from_string(b.read(),content_type='application/zip')

这在我的测试存储桶中创建了 content_type“application/zip”的对象。我不知道你想如何在

BytesIO
中创建这个 zip 文件,但之后应该是可以的。


0
投票

这对我有用:

zip_stream.seek(0)
blob.upload_from_file(zip_stream)

这是一个例子。压缩从 Dataframe 生成的两个 csv 文件并将其上传到存储。

import zipfile
import io

files = [("test1.csv", df1.to_csv()), ("test2.csv", df2.to_csv())]

zip_stream = io.BytesIO()
with zipfile.ZipFile(zip_stream, 'w', compression=zipfile.ZIP_DEFLATED) as new_zip:
    for f in files:
        new_zip.writestr(f[0], f[1])

client = storage.Client()
bucket = client.get_bucket(BUCKET_NAME)
blob = bucket.blob(ZIPFILE_NAME_ON_STORAGE)
zip_stream.seek(0)
blob.upload_from_file(zip_stream)
© www.soinside.com 2019 - 2024. All rights reserved.