5
votes

I'm running web app based on Firebase Realtime Database and Firebase Storage.

I need to upload new images to Firebase google bucket every hour via Python google-cloud-storage lib. Here are the docs.

My code for image upload (img_src path is correct):

    bucket = storage.bucket()
    blob = bucket.blob(img_src)
    blob.upload_from_filename(filename=img_path, content_type='image/png')

Image seem to be uploaded successfully, but when manually viewing it in Firebase Storage, it doesn't load. All the image's specs seem to be correct. Please compare specs of manually uploaded image (loads fine) with corrupted one.

enter image description here

enter image description here

Thanks for help!

1

1 Answers

13
votes

Whenever you upload an image using Firebase Console, an access token will be automatically generated. However, if you upload an image using any Admin SDK or gsutil you will need to manually generate this access token yourself.

Here is an example on how to generate and set an access token for an image using the Admin Python SDK.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage

# Import UUID4 to create token
from uuid import uuid4

cred = credentials.Certificate("path/to/your/service_account.json")
default_app = firebase_admin.initialize_app(cred, {
    'storageBucket': '<BUCKET_NAME>.appspot.com'
})

bucket = storage.bucket()
blob = bucket.blob(img_src)

# Create new token
new_token = uuid4()

# Create new dictionary with the metadata
metadata  = {"firebaseStorageDownloadTokens": new_token}

# Set metadata to blob
blob.metadata = metadata

# Upload file
blob.upload_from_filename(filename=img_path, content_type='image/png')

Here is quick explanation:

  • Import the UUID4 library to create a token. from uuid import uuid4
  • Create a new UUID4. new_token = uuid4()
  • Create a new dictionary with the key-value pair. metadata = {"firebaseStorageDownloadTokens": new_token}
  • Set it as the blob's metadata. blob.metadata = metadata
  • Upload the file. blob.upload_from_filename(...)

This solution can be implemented for any Admin SDK.

Firebase Support says that this is being fixed, but I think anyone having this problem should go this way instead of waiting for Firebase to fix this.