首页 > 解决方案 > Python 的 google-cloud-storage 中是否有与 `refFromUrl` 等价的东西?

问题描述

Firebase API 提供了一个方便的函数Storage::refFromUrl ( source ),它将 aURL转换为存储引用。

源码(location.ts)看,它看起来是一个简单的正则表达式。

是否有等效的 Python 方法可与google-cloud-storageAPI 一起使用以获取存储桶和路径?

标签: pythongoogle-cloud-storage

解决方案


这是一个简单的正则表达式。以下是我根据参考 Javascript 实现在几分钟内整理的内容:

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)

我已经要求将它添加到 Firebase 功能列表中,如果它出现,我希望它会在firebase_admin.storage中公开

使用bucket并且path可以直接创建存储引用。


推荐阅读