implementing firebase in python using firebase admin sdk
Firebase is a mobile and web application development platform by Google. Firebase platform has approx 18 products ready to be implemented in the project.
Features of firebase can be implemented in python using Firebase Admin SDK for Python. In this post, we will tackle Firebase Authentication and Storage which are essential for most of the projects.
Create a Firebase App
Open your Firebase Console and create an app or find an existing app.
Download the Firebase config file which is in JSON format this file is needed to be mentioned inside your project. In the project‘s console, the config file can be downloaded from Settings > Project Settings >Service Accounts > Firebase Admin SDK > Generate New Private Key
Install the Firebase SDK
Install the Firebase Admin SDK for python using pip.
1
pip install firebase_admin
Configure SDK in Python Project
Importing Firebase Admin to project
1
fromfirebase_adminimportcredentials
Creating a Firebase app instance
1
2
3
4
defcreate_firebase_app():cred=credentials.Certificate('PATH OF FIREBASE SERVICE FILE ')firebase=firebase_admin.initialize_app(cred)returnfirebase
1
firebase_instance=create_firebase_app()
Implementing Firebase Auth
Firebase Auth is a service that can authenticate users using only client-side code.
Importing Firebase Auth to project
1
fromfirebase_adminimportauth
Creating a User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defcreate_user(username,name,email,password):try:auth.create_user(email=email,email_verified=True,password=password,display_name=name)returnf'{username} created successfully'exceptExceptionase:returnf'ERROR: {e}'#Taking User Info Logic Here( GUI or Input)
username="tarun_11"name="Tarun"password="PASSWORD"email="[email protected]"#Create User
status=create_user(username=username,name=name,email=email,password=password)print(status)
Retrieving User Data
Functions used to retrieve user data returns UserRecord object using which we can access user information.
# need to specify a uid
user=auth.update_user(uid,email='[email protected]',phone_number='+10000010200',email_verified=True,password='newPassword',display_name='New Name',photo_url='URL',disabled=True)
Deleting User Data
1
auth.delete_user(uid)
Implementing Firebase Storage
Firebase Storage provides secure file uploads and downloads for Firebase apps. The developer can use it to store images, audio, video, or other user-generated content.
Importing Firebase Storage to project
1
fromfirebase_adminimportstorage
Configuring Firebase Storage bucket
1
2
3
4
5
6
7
8
# Edit Create App function to provide storage bucket address
defcreate_firebase_app():cred=credentials.Certificate('PATH OF FIREBASE SERVICE FILE ')firebase=firebase_admin.initialize_app(cred,{'storageBucket':'BUCKET URL FROM FIREBASE STORAGE DASHBOARD'})returnfirebase
1
firebase_instance=create_firebase_app()
Uploading File to Firebase Storage
1
2
3
4
5
6
7
8
9
10
'''
Arguments:
file= File to upload
name=file name by which it is stored in bucket
format (optional)= Format of file (like jpg,png or pdf etc..)
'''defupload_file(file,name,format="image/webp"):bucket=storage.bucket()blob=bucket.blob(name)blob.upload_from_filename(file,content_type=format)
1
2
# Uploading a file in root
upload_file(file='image.webp',name='cover.webp',format="image/webp")
1
2
# Uploading a file in a folder
upload_blob(file='image.webp',name=os.path.join(FOLDER_NAME,'cover.webp'),format="image/webp")
Delete File from Firebase Storage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'''
Arguments:
filename= Name of file to delete
folder_name (optional)= Name of folder inside bucket where specified file resides
'''defdelete_file(filename,folder_name=None):bucket=storage.bucket()deleted=Noneiffolder_name:blob=bucket.blob(os.path.join(folder_name,filename))deleted=blob.delete()else:blob=bucket.blob(filename)deleted=blob.delete()returndeleted
1
2
# Deleting a file from root
deleted_file=delete_file('cover.webp')
1
2
# Deleting a file from a folder
deleted_file=delete_file(os.path.join(FOLDER_NAME,'cover.webp'))
Making a File Public
1
2
3
4
5
6
7
8
9
10
11
12
13
'''
Arguments:
filename= Name of file to delete
folder_name (optional)= Name of folder inside bucket where specified file resides
'''defmake_file_public(filename,folder_name=None):bucket=storage.bucket()iffolder_name:blob=bucket.blob(os.path.join(folder_name,filename))blob.make_public()else:blob=bucket.blob(filename)blob.make_public()
1
2
# Making file public from a folder
make_file_public('cover.webp')
1
2
# Making file public from root
make_file_public(os.path.join(FOLDER_NAME,'cover.webp'))
Generating access URL for a file
The saved file inside bucket needs to be accessed in some manner most common way to access a file is through URL. Firebase provides a way to generate
Signed URL- URL which is valid for a specific time after which they get expired.
Public URL- URL which is valid till the file is present in storage. To get a public URL file should be public.
1
2
3
4
5
6
7
8
9
10
# Signed URL
'''
Arguments:
name=Name of file for which url is to generate
minutes (optional)=Expiry time of url
'''defgenerate_signed_url(name,minutes=43800):bucket=storage.bucket()blob=bucket.blob(name)returnblob.generate_signed_url(timedelta(minutes=minutes))
1
2
# generating signed url for a file in root of bucket
url=generate_signed_url('cover.webp')
1
2
# generating signed url for file inside a folder
url=generate_signed_url(os.path.join(FOLDER_NAME,'cover.webp'))
1
2
3
4
5
6
7
8
9
# Public URL
'''
Arguments:
Name=Name of file for which url is to generate
'''defgenerate_public_url(name):bucket=storage.bucket()blob=bucket.blob(name)returnblob.public_url
1
2
# generating public url for a file in root of bucket
url=generate_public_url('cover.webp')
1
2
# generating public url for file inside a folder
url=generate_public_url(os.path.join(FOLDER_NAME,'cover.webp'))
This article just provides a configuration of Firebase and basic implementation of some features of Firebase. For more references please refer to Firebase docs.