Flask电商应用从Firebase Storage拉取图片时含文件夹链接的解决方法
解决Firebase Storage列出图片时包含文件夹的问题
在Flask电商应用中调用Firebase Storage获取图片链接时,list_blobs方法返回的结果会包含images/文件夹本身的条目,导致生成的image_urls列表混入无效链接。
问题原因
Firebase Storage中的“文件夹”本质是带前缀的空Blob对象,list_blobs(prefix="images/")会返回所有匹配该前缀的对象,包括这个代表文件夹的空Blob。
解决方案
修改生成image_urls的列表推导式,添加过滤条件排除文件夹条目,有两种常用方式:
通过文件名后缀判断
文件夹的name属性会以/结尾,直接过滤这类条目:image_urls = [ blob.generate_signed_url(expiration=timedelta(minutes=15), method="GET") for blob in blobs if not blob.name.endswith('/') ]通过文件大小判断
代表文件夹的Blob大小为0,过滤所有大小为0的对象:image_urls = [ blob.generate_signed_url(expiration=timedelta(minutes=15), method="GET") for blob in blobs if blob.size > 0 ]
修改后的完整函数
def get_image_urls(): # initializing firebase-admin SDK if not firebase_admin._apps: cred = credentials.Certificate('firebase-credentials.json') firebase_admin.initialize_app(cred) # getting a reference to the Firebase Storage bucket bucket = storage.bucket(name="bucket_name") # listing the images in the "images" directory in Firebase Storage bucket blobs = bucket.list_blobs(prefix="images/") # 过滤文件夹条目,仅保留图片文件的签名URL image_urls = [ blob.generate_signed_url(expiration=timedelta(minutes=15), method="GET") for blob in blobs if not blob.name.endswith('/') ] return image_urls
内容的提问来源于stack exchange,提问作者dartHTh0t
相关产品推荐
相关产品推荐

