Firebase Storage - error with uploading png image via Python google-cloud-storage lib

我怕爱的太早我们不能终老 提交于 2020-07-21 07:45:09

问题


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.

Thanks for help!


回答1:


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.



来源:https://stackoverflow.com/questions/60080133/firebase-storage-error-with-uploading-png-image-via-python-google-cloud-storag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!