如何在python中从Google存储直接将文件发送到客户端?

问题描述

我想根据要求从Google存储向客户端发送任何文件,但是要在服务器上本地下载。我不会在本地下载,而是以任何方式直接将文件发送到客户端。

目前,我正在通过这种方式下载

def download_file(self,bucket,key,path_to_download):
        bucket = gc_storage.storage_client.bucket(bucket)
        blob = bucket.blob(key)
        blob.download_to_filename(path_to_download)

解决方法

我不认为有API方法可以将数据从GCS加载到通用的第三位置,尽管某些特定用例存在一些数据传输选项。

如评论中所述,如果您愿意至少通过服务器流式传输数据,则from dotenv import load_dotenv from google.cloud.storage import Client from os import getenv from smart_open import open # load environment variables from a file load_dotenv("<path/to/.env") # get the path to a service account credentials file from an environment variable service_account_path = getenv("GOOGLE_APPLICATION_CREDENTIALS") # create a client using the service account credentials for authentication gcs_client = Client.from_service_account_json(service_account_path) # use this client to authenticate your transfer transport = {"client": gcs_client} with open("gs://my_bucket/my_file.txt",transport_params=transport) as f_in: with open("gs://other_bucket/my_file.txt","wb",transport_params=transport) as f_out: for line in f_in: f_out.write(line) 在此处可以作为一种选择。也许是这样的:

from smart_open import open

with open("gs://my_bucket/my_file.txt") as f_in:
    with open("gs://other_bucket/my_file.txt","wb") as f_out:
        for line in f_in:
            f_out.write(line)

这里,我假设您没有默认通过身份验证,因此已经写出了使用服务帐户执行此操作的完整机制。我的理解是,如果您的计算机已设置为使用某些默认凭据连接到GCS,则可以删除其中的大部分信息:

# ... [obtain gcs_client as before] ...

my_bucket = gcs_client.get_bucket("my-bucket")
other_bucket = gcs_client.get_bucket("other-bucket")

my_file = my_bucket.get_blob("my-file.txt")

my_bucket.copy_blob(my_file,other_bucket)

还请注意,我编写此代码的方式就像您将文件从一个GCS存储桶传输到另一个GCS存储桶一样-但这实际上是其中 内置API方法的一种情况实现目标!

with

听起来您实际上想要做的是将数据传递给第三方,因此内部的{{1}}语句将需要替换为您实际使用的任何实现。