【问题标题】:Get Public URL for File - Google Cloud Storage - App Engine (Python)获取文件的公共 URL - Google Cloud Storage - App Engine (Python)
【发布时间】:2014-01-18 18:25:18
【问题描述】:

有没有相当于getPublicUrl PHP method的python?

$public_url = CloudStorageTools::getPublicUrl("gs://my_bucket/some_file.txt", true);

我正在使用适用于 Python 的 Google Cloud 客户端库存储一些文件,并且我正在尝试找出一种以编程方式获取我正在存储的文件的公共 URL 的方法。

【问题讨论】:

  • 我不认为它已添加到 python API - 您可以在问题跟踪器中提交功能请求以添加它。

标签: python google-app-engine cloud google-cloud-storage


【解决方案1】:

关于如何构建 URL,请参考https://cloud.google.com/storage/docs/reference-uris

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

http(s)://storage.googleapis.com/[bucket]/[object]

http(s)://[bucket].storage.googleapis.com/[object]

例子:

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

会输出这个:

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

【讨论】:

  • 如果它在子文件夹中,那么 'my_bucket.storage.googleapis.com/subfolder/some_file.txt'
  • 截至 2018 年,该模式已更新为:https://storage.cloud.google.com/[BUCKET_NAME]/[OBJECT_NAME] 以上链接仍然有效并包含更多信息。
  • 答案中的链接指向cloud.google.com/storage/docs/access-public-data,表示使用http://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]
  • 截至 6 月 19 日,您无法通过 python 中的 gcloud api 执行此操作。我相信他们将在即将推出的功能中提供此功能。
【解决方案2】:

丹尼尔,艾萨克 - 谢谢你们。

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

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

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

blobKey = blobstore.create_gs_key('/gs' + gcs_filename)

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

app = webapp2.WSGIApplication([
...
    ('/blobstore/serve', scripts.FileServer.GCSServingHandler),
...

文件服务器.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')

【讨论】:

  • 要明确一点,使用 send_blob()images.get_serving_url() 仍然计入更昂贵的 GAE 带宽配额,而不是更便宜的 GCS 出口配额,对吗?
  • 我认为 get_serving_url 产生的 url 是 GCS 直接的,因此更便宜。它具有将自动图像调整大小作为 url 参数的一部分应用的额外好处
【解决方案3】:

它不可用,但我已提交a bug。同时,试试这个:

import urlparse

def GetGsPublicUrl(gsUrl, secure=True):
  u = urlparse.urlsplit(gsUrl)
  if u.scheme == 'gs':
    return urlparse.urlunsplit((
        'https' if secure else 'http',
        '%s.storage.googleapis.com' % u.netloc,
        u.path, '', ''))

例如:

>>> GetGsPublicUrl('gs://foo/bar.tgz')
'https://foo.storage.googleapis.com/bar.tgz'

【讨论】:

【解决方案4】:

您需要使用图片 API 中的get_serving_url。正如该页面所述,您需要先调用 create_gs_key() 以获取传递给图像 API 的密钥。

【讨论】:

  • 只能用于图像文件,不能用于任何类型的文件。
猜你喜欢
  • 2017-07-08
  • 2015-07-07
  • 2013-01-26
  • 2023-03-23
  • 2018-07-22
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 2014-11-22
相关资源
最近更新 更多