Upload File to Firebase Storage (Python)

Dependencies

pip install firebase_admin

Initialization

Access Storage via firebase_admin

PROJECT_ID = '...'IS_EXTERNAL_PLATFORM = True # False if using Cloud Functionsfirebase_app = Nonedef init_firebase():    global firebase_app    if firebase_app:        return firebase_app    import firebase_admin    from firebase_admin import credentials    if IS_EXTERNAL_PLATFORM:        cred = credentials.Certificate('keys/firebase-adminsdk.json')    else:        cred = credentials.ApplicationDefault()    firebase_app = firebase_admin.initialize_app(cred, {        # 'projectId': PROJECT_ID,        'storageBucket': f"{PROJECT_ID}.appspot.com"    })    return firebase_app

NOTE: To get firebase-adminsdk.json, goto Firebase Console, click on the Gear icon besides Project Overview and select Project Settings -> Service accounts -> Generate new private key.

Access Storage via google.cloud

storage_client = Nonedef init_storage():    global storage_client    if storage_client:        return storage_client    from google.cloud import storage    if IS_EXTERNAL_PLATFORM:        storage_client = storage.Client.from_service_account_json('keys/firebase-adminsdk.json')    else:       storage_client = storage.Client()    '''    app = init_firebase()    storage_client = storage.Client(credentials=app.credential.get_credential(), project=app.project_id)    '''    return storage_client
bucket = storage_client.bucket(bucket_name=f"{PROJECT_ID}.appspot.com")

Usage

Upload and download string

from firebase_admin import storageinit_firebase()# uploadbucket = storage.bucket()blob = bucket.blob('hello.txt')blob.upload_from_string('hello world')# upload via file# blob.upload_from_filename(source_file_name)# downloadoutput = blob.download_as_string()# download to file# blob.download_to_filename(output_file_name)

Load and Save JSON

def load_json(name):    init_firebase()    bucket = storage.bucket()    blob = bucket.blob(name)    # blob.upload_from_string(json.dumps(data, indent=2))    return json.loads(blob.download_as_string())def save_json(name, data):    init_firebase()    bucket = storage.bucket()    blob = bucket.blob(name)    blob.upload_from_string(json.dumps(data, indent=2))

Usage

name = '/tmp/test.json'save_json(name, {'message': 'Hello World'})data = load_json(name)

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.