Files
encoach_backend/helper/firebase_helper.py
2023-09-06 22:19:42 +01:00

66 lines
2.1 KiB
Python

from google.cloud import storage
import os
import uuid
import firebase_admin
from firebase_admin import credentials, firestore
from dotenv import load_dotenv
def download_firebase_file(bucket_name, source_blob_name, destination_file_name):
# Downloads a file from Firebase Storage.
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(f"File downloaded to {destination_file_name}")
return destination_file_name
def upload_file_firebase(bucket_name, destination_blob_name, source_file_name):
# Uploads a file to Firebase Storage.
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
try:
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print(f"File uploaded to {destination_blob_name}")
return True
except Exception as e:
print("Error uploading file to Google Cloud Storage:", e)
return False
def upload_file_firebase_get_url(bucket_name, destination_blob_name, source_file_name):
# Uploads a file to Firebase Storage.
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
try:
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print(f"File uploaded to {destination_blob_name}")
# Make the file public
blob.make_public()
# Get the public URL
url = blob.public_url
return url
except Exception as e:
print("Error uploading file to Google Cloud Storage:", e)
return None
def save_to_db(collection: str, item):
# Initialize Firebase Admin SDK
cred = credentials.Certificate(os.getenv("GOOGLE_APPLICATION_CREDENTIALS"))
firebase_admin.initialize_app(cred)
db = firestore.client()
collection_ref = db.collection(collection)
document_ref = collection_ref.add(item)
if document_ref:
print(f"Document added with ID: {document_ref}")
return True
else:
return False