[英]How to read a Google Cloud Storage file from Google App Engine
[英]How to read non-text file stored on Google Cloud Storage from Google Cloud Functions
我需要從 Google Cloud Functions 讀取文件。 我要讀取的文件托管在 Google Cloud Storage 中。 該文件不是阻止我使用download_as_string
類的文本文件。
到目前為止,我已經嘗試以所有標准方式直接從對象讀取gcs.open(file)
,但是沒有定義 gcs (即使我確實在文件頂部將 cloudstorage 作為 gcs 導入)。
我能找到的最接近的事情是如何使用 python 從谷歌雲讀取 mp3 數據(我想讀取一個 MP4 文件)但后來我嘗試了,使用blob_uri = gf.open(r'gs://' + bucket_name + '/' + file_name)
我總是收到以下錯誤FileNotFoundError: [Errno 2] No such file or directory: gs://<yourbucket>/<filename>
我也試過bucket.get_blob(data['name'])
和bucket.get_blob(data)
。
因為是mp3文件,所以不能以字符串形式打開(比如file = blobfile.download_as_string()
)
我還嘗試使用請求嘗試將文件轉換為比特率,然后讀取該數據,但是,由於只讀訪問雲功能需要(我也嘗試直接上傳到雲存儲,但是因為 CS 返回一個博客,我無法寫入文件)。
是否可以從 Google Cloud Functions 直接從直接托管在 Google Cloud Storage 上的(非文本)文件讀取? 如果是這樣,我將如何做到這一點?
請記住:blob 表示二進制大對象。 因此,是的,可以讀取非字符串 blob!
在 Python 中,您可以按照文檔中的描述download_to_filename
您可以讀取駐留在谷歌雲存儲中的文件的最佳方式,然后通常將它們用作文件系統,使用模塊“gcsfs”。 在您的 requirements.txt 文件中包含 gcsfs。
import gcsfs
fs = gcsfs.GCSFileSystem(project=projectid)
with fs.open(filename) as filename:
file = filename.read()
簡單的!
我不確定您將什么導入為“gf”,但您得到的錯誤可能是因為期望文件系統路徑或字符串格式不正確。
此外,您將無法將 blob 下載到文件系統,因為您無法使用 Cloud Functions 將其寫入磁盤,但是您可以檢索 blob 的二進制數據,對其進行處理並將其再次上傳到存儲桶。
1.- 獲取Blob :
client = storage.Client()
bucket = client.get_bucket("my-bucket")
assert isinstance(bucket.get_blob("/path/to/blob.txt"), Blob)
# <Blob: my-bucket, /path/to/blob.txt>
assert not bucket.get_blob("/does-not-exist.txt")
# None
請注意, get_blob函數需要存儲桶內的相對路徑。
2.- 處理您的數據(請記住,這將是二進制數據)。
3.- 將生成的 blob 上傳到您的存儲桶,您可以使用 upload_from_string 方法,因為文檔指出它也接受二進制數據,但您必須將內容類型指定為“application/octet-stream”,因為默認值為“text/plain”和你的二進制數據在技術上不是“mp3”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.