我正在尝试从函数中编写一个新文件(而不是上传一个现有文件)到桶中。
google-cloud-storage,但它没有用于存储桶的"open“属性。GoogleAppEngineCloudStorageClient,但该函数无法与此gcs-client,但由于需要JSON文件,因此无法传递函数内部的凭据。F 211
任何想法都将不胜感激。
谢谢。
发布于 2020-01-18 12:19:59
您必须在本地创建文件,然后将其推送到GCS。不能使用open在GCS中动态创建文件。
为此,您可以在内存文件系统中的/tmp目录中写入。顺便说一句,您将永远无法创建一个比函数允许的内存量更大的文件,减去代码的内存占用。使用2Gb的函数,您可以预期最大文件大小约为1.5Gb。
注意: GCS不是一个文件系统,您不必像这样使用它
发布于 2020-06-06 00:48:39
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()发布于 2021-12-15 15:12:05
您现在可以直接将文件写入。不再需要在本地创建一个文件,然后上传它。
您可以如下所示使用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
https://stackoverflow.com/questions/59799941
复制相似问题