Intermediate

Jul 5, 2024

Updating your Firebase with Python

Introduction

Managing your Firebase database using Python is a powerful and efficient way to handle various backend tasks. While these operations can be performed using Cloud Functions or an Admin tool in FlutterFlow, Python offers a more flexible and straightforward approach for many developers. In this tutorial, we'll guide you through the process of updating your Firebase database withPython.

Prerequisites

  1. Installed Python

  2. Basic Python knowledge

  3. Firebase Admin SDK JSON file

To get a Firebase Admin SDK JSON file:

  1. Go to your Firebase console.

  2. Navigate to Project Settings => ServiceAccounts.

  3. Click on "Generate new private key" and save the file securely.

__wf_reserved_inherit
  • Get the Firebase Admin SDK json file (private key).


Step-by-step guide

1. Setup

First, we need to install the necessary Python libraries to interact with Firebase.

pip install firebase-admin matplotlib

Next, we import the required modules and initialize Firebase:

import firebase_admin
from firebase_admin import credentials, firestore
import matplotlib.pyplot as plt

# Initialize Firebase Admin SDK
cred = credentials.Certificate('path_to_json')
firebase_admin.initialize_app(cred)

# Get a reference to the Firestore database
db = firestore.client()

2. Updating all documents

Let's say you want to set a field promo_enabled to true for all users. This can be done quickly with Python.

def update_users_promo():
    users_ref = db.collection('users')
    users = users_ref.stream()

    # Counter for updated documents
    updated_count = 0

    # Update each user where promo_enabled is not set
    for user in users:
        user_ref = users_ref.document(user.id)
        user_ref.update({
            'promo_enabled': True,
        })
        updated_count += 1

    print(f"Update completed. {updated_count} documents were updated.")

update_users_promo()

The users_ref.stream() fetches all documents in the "users" collection. For each user, the promo_enabled field is updated to True. The updated_count keeps track of how many documents were updated.


3. Getting some basic statistics

For more complex tasks like generating analytics, Python is an excellent choice. Let's say you want to graph some data quarterly. Of course you could have software like Tableau or Looker, but let's say you don't. This could be a graph you create:

__wf_reserved_inherit
  • Graph generated by Python from Firebase data.

Now let's say you want to graph the number of posts created over the last three months. Here's some sample code:

from datetime import datetime, timedelta
import matplotlib.dates as mdates

# Define the date range (last 3 months)
end_date = datetime.now()
start_date = end_date - timedelta(days=90)

# Fetch the data from the "open_posts" collection
query = db.collection('open_posts').where('created_time', '>=', start_date).where('created_time', '<=', end_date)
documents = query.get()

# Dictionary to count posts per day
daily_counts = {}

for doc in documents:
    data = doc.to_dict()
    created_time = data['created_time'].date()  # Assuming created_time is a datetime object

    if created_time in daily_counts:
        daily_counts[created_time] += 1
    else:
        daily_counts[created_time] = 1

# Sort the dictionary by date
sorted_daily_counts = dict(sorted(daily_counts.items()))

# Create lists of dates and counts for plotting
dates = list(sorted_daily_counts.keys())
counts = list(sorted_daily_counts.values())

# Plotting
plt.figure(figsize=(10, 5))
plt.plot(dates, counts, marker='o', linestyle='-', label='Posts')

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7))

plt.legend()
plt.title('Number of Posts Created Daily in the Last 3 Months')
plt.xlabel('Date')
plt.ylabel('Number of Posts')
plt.xticks(rotation=45)
plt.tight_layout()

# Show the plot
plt.show()

Fetches data from the posts collection. Processes each document to count posts created on each date. Uses matplotlib to plot the counts of web and non-web posts over time.


Conclusion

Using Python to manage your Firebase database is ideal for one-time jobs or complex tasks that don't need frequent execution. This approach offers flexibility and simplicity, especially for generating detailed analytics or bulk updating documents.

Note: this can be optimized when dealing with large datasets.