Get Public URL for File - Google Cloud Storage - A

2019-03-13 05:57发布

Is there a python equivalent to the getPublicUrl PHP method?

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

I am storing some files using the Google Cloud Client Library for Python, and I'm trying to figure out a way of programatically getting the public URL of the files I am storing.

4条回答
劳资没心,怎么记你
2楼-- · 2019-03-13 06:14

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

查看更多
姐就是有狂的资本
3楼-- · 2019-03-13 06:14

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.

查看更多
仙女界的扛把子
4楼-- · 2019-03-13 06:22

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')
查看更多
狗以群分
5楼-- · 2019-03-13 06:24

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'
查看更多
登录 后发表回答