简体   繁体   中英

Is there an equivalent to `refFromUrl` in google-cloud-storage for Python?

The Firebase API provides a convenience function Storage::refFromUrl ( source ) that converts a URL into a storage reference.

From the source (location.ts) It looks like it's a straightforward Regular expression.

Is there an equivalent Python method that works with the google-cloud-storage API to get the bucket and path?

It's a straightforward regex. Here's what I put together in a few minutes, based on the reference Javascript implementation:

def _urlToBucketPath (url):
    """Convert a Firebase HTTP URL to a (bucket, path) tuple, 
    Firebase's `refFromURL`.
    """
    bucket_domain = '([A-Za-z0-9.\\-]+)'
    is_http = not url.startswith('gs://')

    if is_http:
        path = '(/([^?#]*).*)?$'
        version =  'v[A-Za-z0-9_]+'
        rex = (
            '^https?://firebasestorage\\.googleapis\\.com/' +
            version + '/b/' + bucket_domain + '/o' + path)
    else:
        gs_path = '(/(.*))?$'
        rex = '^gs://' + bucket_domain + gs_path

    matches = re.match(rex, url, re.I)
    if not matches:
        raise Exception('URL does not match a bucket: %s' % url)

    bucket, _, path = matches.groups()

    if is_http:
        path = urllib.parse.unquote(path)

    return (bucket, path)

I've asked that it be added to the Firebase features list, and if it shows up I expect it'd be exposed in firebase_admin.storage

With the bucket and path it's straightforward to create a storage reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM