Python - Firebase DB reference error - python

I need to update certain node in my Firebase DB, so this is what I'm doing:
from firebase_admin import db
def update_data_in_firebase(gid, account_id, location_id, data_to_update):
firebase_url = 'saved_locations/{}/accounts/{}/locations/{}'.format(gid, account_id, location_id)
ref = db.reference(path=firebase_url)
ref.update(data_to_update)
So, the code above is what I'm trying to do to update the data in the Firebase node, but I'm getting this error:
Invalid databaseURL option: "None". databaseURL must be a non-empty URL string.
Of course, I checked out the firebase URL and it matches, so the problem is not the URL, or, I'm missing something with the path, I mean, should I use absolute insted of relative path.

As mentioned in the comments of the question, the databaseURL was not defined.
Answer:
cred = credentials.Certificate('your_config.json')
firebase_admin = firebase_admin.initialize_app(cred, {'databaseURL': 'https://your-firebase-db'})
In the main docs of Firebase, I couldn't find the error on my app initialization:
Firebase Admin Docs
But in the Realtime Database - Admin (Get Started), there is a snippet where they initialize the Firebase App defining the databaseURL

Related

Why I get this error on python firebase-admin initialize_app()?

when I was trying to connect google firebase real time database, I got this error:
ValueError: The default Firebase app already exists. This means you called
initialize_app() more than once without providing an app name as the second argument. In
most cases you only need to call initialize_app() once. But if you do want to initialize
multiple apps, pass a second argument to initialize_app() to give each app a unique name.
Here is my code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred = credentials.Certificate('firebase-sdk.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://test-139a6-default-rtdb.firebaseio.com/'
})
You only need to initialize (create) the app once. When you have created the app, use get_app instead:
# The default app's name is "[DEFAULT]"
firebase_admin.get_app(name='[DEFAULT]')
You need to initialize the Admin SDK only once. You can check if the Admin SDK is already initialized using this if statement:
if not firebase_admin._apps:
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://test-139a6-default-rtdb.firebaseio.com/'
})

Connect with Google Cloud MySQL through Python; how to access table?

After following this tutorial, I am able to run a script that prints all the details of my database. However, I have no clue as to how to do something with said database! Here's my code:
from google.oauth2 import service_account
import googleapiclient.discovery
import json
SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
response = sqladmin.instances().list(project='single-router-309308').execute()
print(json.dumps(
response, sort_keys=True, indent=2))
sqladmin.close()
Which prints all the info. I tried various things to reach my table, products, but I can't get it to work and keep getting a AttributeError: 'Resource' object has no attribute 'execute' (or 'list') exception. I tried stuff like this:
response = sqladmin.projects().list().execute()
To view my tables as well, but it doesn't work. I believe this is the correct approach since I can connect, but I haven't figured it out yet. Anybody know the answer?
As per the documentation, you should be able to get access to your table using the below code.
Note that you have an sql project, then an instance on the project, then a database in the instance, then your table is nested inside that database.
from pprint import pprint
# Project ID of the project that contains the instance.
project = 'single-router-309308'
# Database instance ID. You should have this from the above printout
instance = 'my-instance'
# Name of the database in the instance. You can look this up if you arent sure by logging into google cloud for your project. Your table is inside this database.
database = 'my-database'
request = service.databases().get(project=project, instance=instance, database=database)
response = request.execute() #returns a dictionary with the data
pprint(response)
I would suggest you take a look at the REST API references for CLoud SQL for MySQL for further reading (https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/databases/get).

How to delete a image file from Google firebase Storage using python

I am currently in the process of creating a Web App (Flask) where users can log in and upload photos to Google Firebase. At one point in the code I was initially saving user uploaded photos to a local folder, but when deployed this doesn't work correctly so I decided to temporarily store it in Google Storage, analyze the faces in it, then delete it. However, I am unable to delete it from Google Storage for some reason.
Firebase Initilizations:
import pyrebase
from pyrebase.pyrebase import storage
import firebase_admin
from firebase_admin import storage, credentials
firebase = pyrebase.initialize_app(json.load(open('firebase/firebaseConfig.json')))
auth = firebase.auth()
db = firebase.database()
storage = firebase.storage()
I have not needed to delete the photos in storage before, but I am able to store Images as well as retrieve their URLs for download as seen below. I am certain the image is stored in my Google Storage and the try fails when I attempt the storage.delete()
try:
storage.child("images/temp/" + filename).put(image, userIdToken)
current_app.logger.info("[UPLOAD-IMAGE] Photo saved, grabbing url")
imageURL = storage.child("images/temp/" + filename).get_url(None)
anazlyzeInfo = recognize.facialRecognition(imageURL)
delete_temp_image_path = "images/temp/" + filename
#storage.delete(imageURL) # same error happens when URL is passed
storage.delete(delete_temp_image_path)
The error described in the exception is: 'Storage' object has no attribute 'bucket'
I looked into this for a while and tried other solutions like StorageRef
and was met with the error 'Storage' has no attribute 'ref'.
I also tried A Service Account following the Google Admin SDK setup but am not sure what to do now that I have:
cred = credentials.Certificate(json.load(open('firebase/fiddl-dev-firebase-adminsdk-stuffdnsnfsnfk.json')))
admin = firebase_admin.initialize_app(cred)
I tried working with this for a while but I could not figure out what was callable with admin.
Was I on the correct path with either of the two fixes I attempted? My use of Firebase was pretty low level before and I would think that deleting would be the same. Thanks!
I’m the OP and I figured out my issue! This GitHub post helped me learn that you need to "add a service account to the config" when getting the 'storage' has not 'bucket' error.
To do this I followed the Firebase Admin Documentation which was pretty straight forward.
However there were 2 main fixes I needed. I fixed this using this Stackoverflow post as a guide.
The first was adding my storageBucket for my app which I was missing above.
admin = firebase_admin.initialize_app(cred, {
'storageBucket': 'fiddl-dev.appspot.com'})
The second issues was when I was trying the bucket = storage.bucket() seen in the same [Stackoverflow] post I was getting the error that storage didn’t have an attribute bucket. This I couldn’t find anything on and was why I made the post.
At the top of my file.py I import:
import pyrebase
from pyrebase.pyrebase import storage
import firebase_admin
from firebase_admin import storage as admin_storage, credentials, firestore
The key being that I added import storage as admin_storage rather than what I had import storage. Essentially I was importing a module named storage twice and it was getting confused.
With that last change I was now able to test the following code that deleted the image from the filepath in Google Firebase Storage specified.
bucket = admin_storage.bucket()
blob = bucket.blob('images/temp/pumpkin.jpg')
print(blob)
blob.delete()

Using firestore in colab with python

i'm trying to use firebase in colab with Python. But there is unsolvable error,
so i need some help.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate('/content/myKey.json')
firebase_admin.initialize_app(cred) # error in this line
db = firestore.client()
ValueError: : The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
What can i do for solving this problem?
i also found similar answer with this, so i tried some many tips in there, like below.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
if not firebase_admin._apps:
cred = credentials.Certificate('/content/foodle-94e80-firebase-adminsdk-zr21t- f02504e9fb.json')
firebase_admin.initialize_app(cred)
else:
app = firebase_admin.get_app()
db = firestore.client(app) # new error in this line
but new error is confusing me.
DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
What can i do?
Looks like there's a default instance of the Firebase app getting initialized somewhere. When the default instance gets created, it uses GOOGLE_APPLICATION_CREDENTIALS instead of the credentials you pass in manually.
You can either provide GOOGLE_APPLICATION_CREDENTIALS to the script, or ignore the default instance of the firebase app and create an explicitly named one.
To create an explicitly named app, change your code to provide a name:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate('/content/myKey.json')
firebase_admin.initialize_app(credential=cred, name='myApp')
db = firestore.client()
To provide GOOGLE_APPLICATION_CREDENTIALS and use the default app:
If you're running your python script from the console, you can provide a value for that by running
export GOOGLE_APPLICATION_CREDENTIALS='/content/myKey.json'
In colab, you need to add this to your script:
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/content/myKey.json"
After this you can run your second example.
(To get the credentials JSON go to this page, select your firebase-adminsdk service account, click 'ADD KEY', 'Create new key', select JSON as your option and download the resulting file.)
In my case it worked with
cred = credentials.Certificate("/content/drive/My Drive/Colab Notebooks/LALALA.json")
firebase_admin.initialize_app(cred)

How to access Firebase Firestore from GCP Cloud Function

I am trying to access a Firebase Firestore DB from a GCP Cloud Function - the function is not part of the Firebase project - so two separate projects. When I config/init the DB I get a permissions error
def hello_world(request):
import firebase_admin
import flask
import json
from flask import request
from firebase_admin import credentials
from firebase_admin import firestore
try:
firebase_admin.initialize_app(options={
'apiKey': '<appkey>',
'authDomain': '<authdomain>',
'databaseURL': '<url>',
'projectId': '<projID>',
'storageBucket': '<bucket>',
'messagingSenderId': '<id>',
'appId': '<app ID>'
})
except:
print("DB already init")
#end db init
db = firestore.client()
# end db setup
I expect/want the result to be to initialize the DB so I can read/write to it, but I get an error:
Error: function crashed. Details:
403 Missing or insufficient permissions.
You seem to be using the app init settings for web, you need to use the sdk key instead. Go to Settings -> Services Account -> and generate your key.
Include the json file instead of those parameters. Hope this helps!

Categories

Resources