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

核能气质少年 提交于 2019-11-27 13:57:28

问题


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.


回答1:


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




回答2:


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.




回答3:


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



回答4:


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'


来源:https://stackoverflow.com/questions/20863747/get-public-url-for-file-google-cloud-storage-app-engine-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!