Created
March 23, 2024 13:40
-
-
Save jha-adrs/a04b476a413050164cfc9b7312824ba4 to your computer and use it in GitHub Desktop.
Firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from firebase_admin import db, storage, credentials, initialize_app | |
from flask import Flask, request | |
# Import the constant from constants.py | |
server = Flask(__name__) | |
cread_obj = credentials.Certificate("./credentials.json") | |
firebaseApp = initialize_app(cread_obj, { | |
"databaseURL": "https://python-248f7-default-rtdb.firebaseio.com/" | |
}) | |
bucket = storage.bucket("python-248f7.appspot.com") | |
# Collection to store the data in the database | |
""" | |
We store only the Key of the image uploaded to the storage, | |
The response of the model, time of the request and the status of the request | |
also, the image is stored in the storage | |
""" | |
def upload_file_to_firebase(filename): | |
try: | |
path = f"images/{filename}" | |
blob = bucket.blob(path) | |
blob.upload_from_filename(path) | |
print(f"File {path} uploaded to firebase storage", | |
"/nPath: ", blob.public_url) | |
# Now add the URL to the database | |
curr_time = datetime.now().isoformat() | |
save_data_to_firebase({"image_url": blob.public_url, | |
"response": "None", "time": curr_time, "status": "pending"}) | |
return blob.public_url | |
except Exception as e: | |
print(f"Error in uploading file to firebase storage: {e}") | |
return None | |
def save_data_to_firebase(data): | |
try: | |
ref = db.reference("/requests") | |
ref.push(data) | |
print("Data saved in the database") | |
except Exception as e: | |
print(f"Error in saving data to firebase database: {e}") | |
def get_data_from_firebase(): | |
try: | |
ref = db.reference("/requests") | |
data = ref.get() | |
return data | |
except Exception as e: | |
print(f"Error in getting data from firebase database: {e}") | |
return None | |
@server.route("/upload", methods=["POST"]) | |
def upload_file(): | |
try: | |
# Get the file from the request | |
file = request.files["file"] | |
# Save the file to the local storage in images folder | |
file.save(f"images/{file.filename}") | |
# Upload the file to the firebase storage | |
url = upload_file_to_firebase(file.filename) | |
return {"url": url} | |
except Exception as e: | |
print(f"Error in uploading file: {e}") | |
return {"error": "Error in uploading file"} | |
if (__name__ == "__main__"): | |
# upload_file_to_firebase() | |
# Start the server | |
print("Done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment