Get Public URL for File - Google Cloud Storage - App Engine (Python)

家住魔仙堡 提交于 2019-11-28 21:36:51
Danny Hong

Please refer to https://cloud.google.com/storage/docs/reference-uris on how to build URLs.

For public URLs, there are two formats:

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

or

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

Example:

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

Will output this:

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

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Daniel, Isaac - Thank you both.

It looks to me like Google is deliberately aiming for you not to directly serve from GCS (bandwidth reasons? dunno). So the two alternatives according to the docs are either using Blobstore or Image Services (for images).

What I ended up doing is serving the files with blobstore over GCS.

To get the blobstore key from a GCS path, I used:

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

Then, I exposed this URL on the server - Main.py:

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

FileServer.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')

It's not available, but I've filed a bug. In the meantime, try this:

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, '', ''))

For example:

>>> GetGsPublicUrl('gs://foo/bar.tgz')
'https://foo.storage.googleapis.com/bar.tgz'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!