[英]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.