我正在尝试从Python Google Cloud Function内部将一个新文件(而不是上传现有文件(写入Google Cloud Storage bucket。
-
我尝试使用
google-cloud-storage
但它没有 存储桶的"打开"属性。 -
我尝试使用 App Engine 库
GoogleAppEngineCloudStorageClient
但该函数无法使用此依赖项进行部署。 -
我尝试使用
gcs-client
但我无法在函数内传递凭据,因为它需要一个JSON
文件。
任何想法将不胜感激。
谢谢。
from google.cloud import storage
import io
# bucket name
bucket = "my_bucket_name"
# Get the bucket that the file will be uploaded to.
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket)
# Create a new blob and upload the file's content.
my_file = bucket.blob('media/teste_file01.txt')
# create in memory file
output = io.StringIO("This is a test n")
# upload from string
my_file.upload_from_string(output.read(), content_type="text/plain")
output.close()
# list created files
blobs = storage_client.list_blobs(bucket)
for blob in blobs:
print(blob.name)
# Make the blob publicly viewable.
my_file.make_public()
您现在可以将文件直接写入 Google Cloud Storage。不再需要在本地创建文件,然后将其上载。
你可以按如下方式使用 blob.open((:
from google.cloud import storage
def write_file():
client = storage.Client()
bucket = client.get_bucket('bucket-name')
blob = bucket.blob('path/to/new-blob.txt')
with blob.open(mode='w') as f:
for line in object:
f.write(line)
您可以在此处找到更多示例和片段: https://github.com/googleapis/python-storage/tree/main/samples/snippets
您必须在本地创建文件,然后将其推送到 GCS。您无法使用打开在 GCS 中动态创建文件。
为此,您可以在内存文件系统的/tmp
目录中写入。顺便说一下,您将永远无法创建大于函数允许的内存量减去代码内存占用量的文件。使用具有2Gb的功能,您可以期望最大文件大小约为1.5Gb。
注意:GCS不是文件系统,您不必像这样使用它
>编辑1自从我的回答以来,情况发生了变化:
- 现在可以写入容器中的任何目录(不仅是
/tmp
( - 您可以在 GCS 中流式写入文件,也可以在 CLoud Run 上以流式模式接收它。下面是一个将写入流式传输到 GCS 的示例。
注意:流写入停用校验和验证。因此,在文件流写入结束时不会进行完整性检查。