Search code examples
flaskfirebase-storagefirebase-admin

While trying to download images from firebase storage for flask app, I am getting image folder link in return


I have stored images in a firebase storage and I am trying to download those images for my flask e-commerce app. here's the code:

shop_page = Blueprint('shop', __name__, template_folder='templates/shop', static_folder='static/shop')

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/")
    
    # creating a list of image URLs by directly using blob.generate_signed_url
    image_urls = [blob.generate_signed_url(expiration=timedelta(minutes=15), method="GET") for blob in blobs]
    return image_urls

@shop_page.route('/', methods=['GET'])
def shop_base():
    image_urls = get_image_urls()
    return render_template('shop/shop_base.html',image_urls=image_urls)

The issue is the image_urls I generate from the blobs also includes the folder the images are stored in. What do I need to modify to make sure image_urls include only images, not the image folder itself.


Solution

  • You can check it by verifying if the last character is a /, this way:

    image_urls = [blob.generate_signed_url(expiration=timedelta(minutes=15), method="GET") for blob in blobs if not blob.name.endswith('/')]