Upload File to Firebase Storage (Python)

January 2, 2020

Dependencies

pip install firebase_admin

Initialization

Access Storage via firebase_admin

PROJECT_ID = '...'

IS_EXTERNAL_PLATFORM = True # False if using Cloud Functions

firebase_app = None

def 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 = None

def 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 storage

init_firebase()

# upload
bucket = storage.bucket()
blob = bucket.blob('hello.txt')
blob.upload_from_string('hello world')
# upload via file
# blob.upload_from_filename(source_file_name)

# download
output = 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.