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.

https://firebase.google.com/

Create a Firebase App

  1. Open your Firebase Console and create an app or find an existing app.

  2. 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

  1. Importing Firebase Admin to project
1
from firebase_admin import credentials
  1. Creating a Firebase app instance
1
2
3
4
def create_firebase_app():
 cred = credentials.Certificate('PATH OF FIREBASE SERVICE FILE ')
 firebase=firebase_admin.initialize_app(cred)
 return firebase
1
firebase_instance=create_firebase_app()

Implementing Firebase Auth

Firebase Auth is a service that can authenticate users using only client-side code.

  1. Importing Firebase Auth to project
1
from firebase_admin import auth
  1. Creating a User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def create_user(username,name,email,password):
 try:
  auth.create_user(email=email,email_verified=True,password=password,display_name=name)
  return f'{username} created successfully'
 except Exception as e:
  return f'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)
  1. Retrieving User Data

Functions used to retrieve user data returns UserRecord object using which we can access user information.

  • Using User Id
1
2
3
def get_user(id):
 user = auth.get_user(id)
 return user
  • Using Email Id
1
2
3
def get_user(email):
 user = auth.get_user_by_email(email)
 return user
  • All Users
1
2
for user in auth.list_users().iterate_all():
 print('User: ' + user.uid)
  1. Updating User Data
1
2
3
4
5
6
7
8
9
10
11
12
# 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
 )
  1. 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.

  1. Importing Firebase Storage to project
1
from firebase_admin import storage
  1. Configuring Firebase Storage bucket
1
2
3
4
5
6
7
8
# Edit Create App function to provide storage bucket address

def create_firebase_app():
 cred = credentials.Certificate('PATH OF FIREBASE SERVICE FILE ')
 firebase=firebase_admin.initialize_app(cred, {
 'storageBucket': 'BUCKET URL FROM FIREBASE STORAGE DASHBOARD'
 })
 return firebase
1
firebase_instance=create_firebase_app()
  1. 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..)
'''
def upload_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")
  1. 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
'''
def delete_file(filename,folder_name=None):
 bucket=storage.bucket()
 deleted=None
 if folder_name:
  blob=bucket.blob(os.path.join(folder_name,filename))
  deleted=blob.delete()
 else:
  blob=bucket.blob(filename)
  deleted=blob.delete()
  return deleted
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'))
  1. 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
'''
def make_file_public(filename,folder_name=None):
 bucket=storage.bucket()
 if folder_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'))
  1. 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
'''
def generate_signed_url (name,minutes=43800):
 bucket=storage.bucket()
 blob=bucket.blob(name)
 return blob.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
'''
def generate_public_url (name):
 bucket=storage.bucket()
 blob=bucket.blob(name)
 return blob.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.

Thanks for being till last.😊😊

References:

Firebase Docs

Google Cloud Blob Docs