获取文件的公共URL - Google云端存储 - App Engine(Python)

orc*_*man 12 python cloud google-app-engine google-cloud-storage

是否有一个等效于getPublicUrl PHP方法的python ?

$public_url = CloudStorageTools::getPublicUrl("gs://my_bucket/some_file.txt", true);
Run Code Online (Sandbox Code Playgroud)

我正在使用Google Cloud Client Library for Python存储一些文件,我正试图找出一种以编程方式获取我存储的文件的公共URL的方法.

Dan*_*ong 38

有关如何构建网址,请参阅https://cloud.google.com/storage/docs/reference-uris.

对于公共URL,有两种格式:

http(s)://storage.googleapis.com/[bucket]/[object]
Run Code Online (Sandbox Code Playgroud)

要么

http(s)://[bucket].storage.googleapis.com/[object]
Run Code Online (Sandbox Code Playgroud)

例:

bucket = 'my_bucket'
file = 'some_file.txt'
gcs_url = 'https://%(bucket)s.storage.googleapis.com/%(file)s' % {'bucket':bucket, 'file':file}
print gcs_url
Run Code Online (Sandbox Code Playgroud)

输出这个:

https://my_bucket.storage.googleapis.com/some_file.txt

  • 截至2018年,该模式已更新为:"https://storage.cloud.google.com/ [BUCKET_NAME]/[OBJECT_NAME]"上述链接仍然有效,并包含更多信息. (2认同)

Dan*_*man 5

您需要使用get_serving_urlImages API.如该页面所述,您需要先调用create_gs_key()以获取传递给Images API的密钥.

  • 您只能将其用于图像文件,而不能用于任何类型的文件. (4认同)

orc*_*man 4

丹尼尔、艾萨克——谢谢你们俩。

在我看来,Google 故意让您不要直接从 GCS 提供服务(带宽原因?不知道)。因此,根据文档,两种替代方案是使用 Blobstore 或图像服务(用于图像)。

我最终所做的是通过 GCS 使用blobstore提供文件。

为了从 GCS 路径获取 blobstore 密钥,我使用了:

blobKey = blobstore.create_gs_key('/gs' + gcs_filename)
Run Code Online (Sandbox Code Playgroud)

然后,我在服务器上公开了这个 URL - Main.py:

app = webapp2.WSGIApplication([
...
    ('/blobstore/serve', scripts.FileServer.GCSServingHandler),
...
Run Code Online (Sandbox Code Playgroud)

文件服务器.py:

class GCSServingHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self):
        blob_key = self.request.get('id')
        if (len(blob_key) > 0):
            self.send_blob(blob_key)
        else: 
            self.response.write('no id given')
Run Code Online (Sandbox Code Playgroud)