![](/img/trans.png)
[英]How can I use a Google Cloud Function to push a file from a Cloud Storage bucket into an instance?
[英]Writing a new file to a Google Cloud Storage bucket from a Google Cloud Function (Python)
我正在嘗試從 Python Google Cloud Function 內部將新文件(而不是上傳現有文件)寫入 Google Cloud Storage 存儲桶。
我嘗試使用google-cloud-storage
但它沒有google-cloud-storage
桶的“打開”屬性。
我嘗試使用 App Engine 庫GoogleAppEngineCloudStorageClient
但該函數無法使用此依賴項進行部署。
我嘗試使用gcs-client
但我無法在函數內部傳遞憑據,因為它需要一個JSON
文件。
任何想法將不勝感激。
謝謝。
您必須在本地創建文件,然后將其推送到 GCS。 您不能使用 open 在 GCS 中動態創建文件。
為此,您可以在/tmp
目錄中寫入內存文件系統。 順便說一句,您將永遠無法創建大於函數允許的內存量減去代碼的內存占用量的文件。 使用 2Gb 的函數,您可以預期最大文件大小約為 1.5Gb。
注意:GCS 不是文件系統,你不必像這樣使用它
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-name.txt')
## Use bucket.get_blob('path/to/existing-blob-name.txt') to write to existing blobs
with blob.open(mode='w') as f:
for line in object:
f.write(line)
您可以在此處找到更多示例和片段: https : //github.com/googleapis/python-storage/tree/main/samples/snippets
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.