"No such file or directory" with firebase_admin python library - python

I want to retrieve some data by a firebase database with using the official library for python (firebase_admin) instead of pyrebase or python-firebase.
I try to execute the following lines of code:
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
cred = credentials.Certificate('https://project_name.firebaseio.com/.json')
firebase_admin.initialize_app(cred)
result = db.Query.get()
but then I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'https://project_name.firebaseio.com/.json'
even though when I enter this url on my browser (with project_name replaced with my real project name) I am getting the json of data from the database.
How can I fix this error?

The Certificate should point to a local file with your credentials/certificate. You are instead pointing it to your database URL, which is not a local file, so the library throws an error.
From the documentation on initializing the Python SDK:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Fetch the service account key JSON file contents
cred = credentials.Certificate('path/to/serviceAccountKey.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://databaseName.firebaseio.com'
})
# As an admin, the app has access to read and write all data, regardless of Security Rules
ref = db.reference('restricted_access/secret_document')
print(ref.get())

Try this ,this works for me
import os
from firebase_admin import credentials, firestore, initialize_app
# Initialize Firestore DB
data = os.path.abspath(os.path.dirname(__file__)) + "/serviceAccountKey.json"
cred = credentials.Certificate(data)
default_app = initialize_app(cred)
db = firestore.client()

Related

Accessing data in Python from Firestore database without admin privelege

I need to acces Firestore database. I'm working on a projet and need to analys its data but I only have reading rights on it. Therefore I can't generate an SDK key.
I tried with the pyrebase lib but it won't work:
import pyrebase
firebaseConfig = {
"I put here the config with apiKIey, authDomain etc..."}
firebase = pyrebase.initialize_app(firebaseConfig)
#Get a reference to the database service
db = firebase.database()
#data to save
data = db.child("annonces").get()
I believe you are using the wrong python package. You can import firebase and firestore, as well as retrieve a collection as follows:
from firebase_admin import credentials, firestore, initialize_app
firebaseConfig = {...}
cred = credentials.Certificate(firebaseConfig)
firebase_app = initialize_app(cred)
db = firestore.client()
data = []
announce_docs = db.collection("users").stream()
for doc in announce_docs:
announcement = doc.to_dict()
data.append(user)
You can find more info in the Offical Docs

How to Initialize Firebase Admin SDK in Cloud Function (Python)

I found a similar question on here, but it was for JavaScript and I am using Python. I'm trying to use the Firebase-Admin SDK so I can verify Firebase Authentication id_tokens in my cloud function. In my requirements.txt I have included firebase-admin, and my main.py file looks like this:
from firebase_admin import auth
from firebase_admin import credentials
def returnSQLresponse(request):
default_app = firebase_admin.initialize_app()
headers = request.headers
if headers and 'Authorization' in headers:
id_token = headers['Authorization']
decoded_token = auth.verify_id_token(id_token)
uid = decoded_token['uid']
There are probably other problems with the above code, but my main issue is I am getting the error "in returnSQLresponse default_app = firebase_admin.initialize_app() NameError: name 'firebase_admin' is not defined". How do I initialize the Firebase Admin SDK in Python so I can verify this token? I tried following the guide here: https://firebase.google.com/docs/auth/admin/verify-id-tokens#verify_id_tokens_using_the_firebase_admin_sdk. This guide lead me to where I am at now.
Notice that your are importing the auth and credentials modules only and failing to import the firebase_admin module itself and therefore you get the:
NameError: name 'firebase_admin' is not defined
when trying to initialize the app by calling:
...
default_app = firebase_admin.initialize_app()
...
Making sure that firebase-admin is added within your requirements.txt file and making the imports in the following way:
import firebase_admin
import firebase_admin.auth as auth
import firebase_admin.credentials as credentials
def returnSQLresponse(request):
default_app = firebase_admin.initialize_app()
...
should clear the NameError error message.

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)

Initialize Firebase Admin SDK using secret stored in Secret Manager

I am trying to initialize the Firebase Admin SDK within a Cloud Run application, using a separate service account (i.e not the default service account).
The documentation suggests:
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
However, I would like to avoid packaging secrets into the Cloud Run container, so I am retrieving the json file from Secret Manager, and trying to create the credentials, and pass it into: firebase_admin.initialize_app(cred)
import firebase_admin
from google.cloud import secretmanager
from google.oauth2 import service_account
# Create credentials object then initialize the firebase admin client
sec_client = secretmanager.SecretManagerServiceClient()
name = sec_client.secret_version_path(GOOGLE_CLOUD_PROJECT_NUMBER, FIREBASE_SA_SECRET_NAME, "latest")
response = sec_client.access_secret_version(name)
service_account_info = json.loads(response.payload.data.decode('UTF-8'))
creds = service_account.Credentials.from_service_account_info(service_account_info)
firebase_admin.initialize_app(creds)
Error received:
ValueError: Illegal Firebase credential provided. App must be
initialized with a valid credential instance.
Any tips are appreciated.
import firebase_admin
from google.cloud import secretmanager
from google.oauth2 import service_account
# Create credentials object then initialize the firebase admin client
sec_client = secretmanager.SecretManagerServiceClient()
name = sec_client.secret_version_path(GOOGLE_CLOUD_PROJECT_NUMBER, FIREBASE_SA_SECRET_NAME, "latest")
response = sec_client.access_secret_version(name)
service_account_info = json.loads(response.payload.data.decode('utf-8'))
# build credentials with the service account dict
creds = firebase_admin.credentials.Certificate(service_account_info)
# initialize firebase admin
firebase_app = firebase_admin.initialize_app(creds)

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