Skip to content

API reference

cannlytics.firebase

Firebase Module | Cannlytics

Author: Keegan Skeate contact@cannlytics.com
Created: 2/7/2021
Updated: 7/25/2021

Resources:

Description:

A wrapper of firebase_admin to make interacting with the Firestore database and Firebase Storage buckets even easier.

Examples:

import os
import environ

# Get and set all credentials.
env = environ.Env()
env.read_env('.env')
credentials = env('GOOGLE_APPLICATION_CREDENTIALS')
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials
bucket_name = environ.get('FIREBASE_STORAGE_BUCKET')

# Initialize Firebase
db = initialize_firebase()

access_secret_version(project_id, secret_id, version_id)

Access the payload for a given secret version if one exists. The version can be a version number as a string (e.g. "5") or an alias (e.g. "latest").

Warning

Do not print the secret in a production environment.

Parameters:

Name Type Description Default
project_id str

A Firestore project ID.

required
secret_id str

An ID for the secret.

required
version_id str

A version for the secret.

required

Returns:

Type Description
(str)

The secret version's name.

add_secret_version(project_id, secret_id, payload)

Add a new secret version to the given secret with the provided payload. A secret version contains the actual contents of a secret. A secret version can be enabled, disabled, or destroyed. To change the contents of a secret, you create a new version. Adding a secret version requires the Secret Manager Admin role (roles/secretmanager.admin) on the secret, project, folder, or organization. Roles can't be granted on a secret version.

Parameters:

Name Type Description Default
project_id str

A Firestore project ID.

required
secret_id str

An ID for the secret.

required
payload str

The secret.

required

Returns:

Type Description
(str)

The secret version's name.

add_to_array(ref, field, value)

Add an element to a given field for a given reference.

Parameters:

Name Type Description Default
ref str

A document reference.

required
field str

A list field to create or update.

required
value dynamic

The value to be added to the list.

required

create_custom_claims(uid, email=None, claims=None)

Create custom claims for a user to grant granular permission. The new custom claims will propagate to the user's ID token the next time a new one is issued.

Parameters:

Name Type Description Default
uid str

A user's ID.

required
email str

A user's email.

None
claims dict

A dictionary of the user's custom claims.

None

create_custom_token(uid='', email=None, claims=None)

Create a custom token for a given user, expires after one hour.

Parameters:

Name Type Description Default
uid str

A user's ID.

''
email str

A user's email.

None
claims dict

A dictionary of the user's claims.

None

create_document(ref, values)

Create a given document with given values, this leverages the same functionality as update_document thanks to set with merge=True.

Parameters:

Name Type Description Default
ref str

A document reference.

required
values str

A dictionary of values to update.

required

create_id()

Generate a universal ID. Returns: A unique, lexicographic ID, a ULID.

create_id_from_datetime(dt)

Create an ID from an existing datetime.

Parameters:

Name Type Description Default
dt datetime

The time to timestamp the ID.

required

create_log(ref, claims, action, log_type, key, changes=None)

Create an activity log.

Parameters:

Name Type Description Default
ref str

Path to a collection of logs.

required
claims dict

A dict with user fields or a Firestore user object.

required
action str

The activity that took place.

required
log_type str

The log type.

required
key str

A key to recognize the action.

required
changes list

An optional list of changes that took place.

None

create_reference(database, path)

Create a database reference for a given path.

Parameters:

Name Type Description Default
database Firestore Client

The Firestore Client.

required
path str

The path to the document or collection.

required

Returns:

Type Description
(ref)

Either a document or collection reference.

create_secret(project_id, secret_id, secret)

Create a new secret with the given name. A secret is a logical wrapper around a collection of secret versions. Secret versions hold the actual secret material.

Parameters:

Name Type Description Default
project_id str

The project associated with the secret.

required
secret_id str

An ID for the secret.

required
secret str

The secret data.

required

Create a session cookie.

Parameters:

Name Type Description Default
id_token str

A user ID token passed from the client.

required
expires_in timedelta

The time until the session will expire.

None

create_short_url(api_key, long_url, project_name='cannlytics')

Create a short URL to a specified file.

create_user(name, email)

Given user name and email, create an account. If the email is already being used, then nothing is returned.

Parameters:

Name Type Description Default
name str

A name for the user.

required
email str

The user's email.

required

Returns:

Type Description
(tuple)

User object, random password

delete_collection(ref, batch_size=420)

Delete a given collection, a batch at a time.

Parameters:

Name Type Description Default
ref str

A document reference.

required
batch_size int

The number of documents to delete at a time. The default is 420 and the maximum is 500.

420

delete_document(ref)

Delete a given document.

Parameters:

Name Type Description Default
ref str

A document reference.

required

delete_field(ref, field)

Delete a given field from a document.

Parameters:

Name Type Description Default
ref str

A document reference.

required

delete_file(bucket_name, blob_name)

Delete file from GCP bucket.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
blob_name str

The name of the file to delete.

required

delete_user(uid)

Delete a user from Firebase.

Parameters:

Name Type Description Default
uid str

A user's ID.

required

download_file(bucket_name, source_blob_name, destination_file_name, verbose=True)

Downloads a file from Firebase Storage.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
source_blob_name str

The file name to upload.

required
destination_file_name str

The destination file name.

required
verbose bool

Whether or not to print status.

True

download_files(bucket_name, bucket_folder, local_folder, verbose=True)

Download all files in a given Firebase Storage folder.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
bucket_folder str

A folder in the storage bucket.

required
local_folder str

The local folder to download files.

required
verbose bool

Whether or not to print status.

True

export_data(db, ref, data_file)

Export data from Firestore.

Parameters:

Name Type Description Default
db Firestore Client required
ref str

A collection or document reference.

required
data_file str

The path to the local data file to upload.

required

Wishlist - Parse fields that are objects into fields. E.g. from pandas.io.json import json_normalize artist_and_track = json_normalize( data=tracks_response['tracks'], record_path='artists', meta=['id'], record_prefix='sp_artist_', meta_prefix='sp_track_', sep='_' )

get_collection(ref, limit=None, order_by=None, desc=False, filters=[])

Get documents from a collection.

Parameters:

Name Type Description Default
ref str

A document reference.

required
limit int

The maximum number of documents to return. The default is no limit.

None
order_by str

A field to order the documents by, with the default being none.

None
desc bool

The direction to order the documents by the order_by field.

False
filters list

Filters are dictionaries of the form {'key': '', 'operation': '', 'value': ''}. Filters apply Firebase queries to the given key for the given value. Operators include: ==, >=, <=, >, <, !=, in, not_in, array_contains, array_contains_any.

[]

Returns:

Type Description
(list)

A list of documents.

get_custom_claims(name)

Get custom claims for a user.

Parameters:

Name Type Description Default
name str

A user ID or user email.

required

get_document(ref)

Get a given document.

Parameters:

Name Type Description Default
ref str

A document reference.

required

Returns:

Type Description
(dict)

Returns the document as a dictionary. Returns an empty dictionary if no data is found.

get_file_url(ref, bucket_name=None, expiration=None)

Return the storage URL of a given file reference.

Parameters:

Name Type Description Default
ref str

The storage location of the file.

required
bucket_name str

The name of the storage bucket.

None

Returns:

Type Description
(str)

The storage URL of the file.

get_id_timestamp(uid)

Get the datetime that an ID was created.

Parameters:

Name Type Description Default
uid str

A unique ID string.

required

get_user(name)

Get a user by user ID or by email.

Parameters:

Name Type Description Default
name str

A user ID, email, or phone number.

required

Returns:

Type Description
(UserRecord)

A Firebase user object.

get_users()

Get all Firebase users.

Returns:

Type Description
(list)

A list of Firebase users.

import_data(db, ref, data_file)

Import data into Firestore.

Parameters:

Name Type Description Default
db Firestore Client required
ref str

A collection or document reference.

required
data_file str

The path to the local data file to upload.

required

Wishlist

It would be desirable for the following functionality to be implemented: - Batch upload - Handle types https://hackersandslackers.com/importing-excel-dates-times-into-pandas/

increment_value(ref, field, amount=1)

Increment a given field for a given reference.

Parameters:

Name Type Description Default
ref str

A document reference.

required
field str

A numeric field to create or update.

required
amount int

The amount to increment, default 1.

1

initialize_firebase()

Initialize Firebase, unless already initialized.

Returns:

Type Description
(Firestore client)

A Firestore database instance.

list_files(bucket_name, bucket_folder)

List all files in GCP bucket folder.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
bucket_folder str

A folder in the storage bucket to list files.

required

remove_from_array(ref, field, value)

Remove an element from a given field for a given reference.

Parameters:

Name Type Description Default
ref str

A document reference.

required
field str

A list field to update.

required
value dynamic

The value to be removed from the list.

required

rename_file(bucket_name, bucket_folder, file_name, newfile_name, verbose=True)

Rename file in GCP bucket.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
bucket_folder str

A folder in the storage bucket.

required
file_name str

The name of the file to rename.

required
newfile_name str

The new name for the file.

required
verbose bool

Whether or not to print status.

True

revoke_refresh_tokens(token)

Revoke a user's refresh token.

Parameters:

Name Type Description Default
token str

The refresh token to authenticate a user.

required

update_custom_claims(uid, email=None, claims=None)

Update custom claims for a user. The new custom claims will propagate to the user's ID token the next time a new one is issued.

Parameters:

Name Type Description Default
uid str

A user's ID.

required
email str

A user's email.

None
claims dict

A dictionary of the user's custom claims.

None

update_document(ref, values)

Update a given document with given values.

Parameters:

Name Type Description Default
ref str

A document reference.

required
values str

A dictionary of values to update.

required

update_user(existing_user, data)

Update a user.

Parameters:

Name Type Description Default
existing_user Firebase user required
data dict

The values of the user to update, which can include email, phone_number, email_verified, diplay_name, photo_url, and disabled.

required

upload_file(bucket_name, destination_blob_name, source_file_name=None, data_url=None, content_type='image/jpg')

Upload file to Firebase Storage.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
destination_blob_name str

The name to save the file as.

required
source_file_name str

The local file name.

None
data_url str

The data URL to upload from a string.

None
content_type str

The content type of the file, when uploading from a string.

'image/jpg'

upload_files(bucket_name, bucket_folder, local_folder, verbose=True)

Upload multiple files to Firebase Storage.

Parameters:

Name Type Description Default
bucket_name str

The name of the storage bucket.

required
bucket_folder str

A folder in the storage bucket to upload files.

required
local_folder str

The local folder of files to upload.

required
verbose bool

Whether or not to print status.

True

Verify a user's session cookie.

Parameters:

Name Type Description Default
session_cookie str

A session cookie to authenticate a user.

required

verify_token(token)

Verify a user's custom token.

Parameters:

Name Type Description Default
token str

The custom token to authenticate a user.

required