Accessing data in Python from Firestore database without admin privelege - python

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

Related

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 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!

How to retrieve image from Firebase Storage using Python?

I have already store my image to Firebase Storage, and I need to take it out by using Python code. Can I retrieve the image by using any URL? Or is there any way to retrieve it out?
Here are the image of how I store it in Firebase Storage:
This is what I use. Hope it helps.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
# Fetch the service account key JSON file contents
cred = credentials.Certificate("credentials.json")
# Initialize the app with a service account, granting admin privileges
app = firebase_admin.initialize_app(cred, {
'storageBucket': '<BUCKET_NAME>.appspot.com',
}, name='storage')
bucket = storage.bucket(app=app)
blob = bucket.blob("<your_blob_path>")
print(blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET'))
It generates a public URL (for 300 secs) for you to download your files.
For example, in my case, I use that URL to display stored pictures in my django website with <img> tag.
Here is the doc for more usefull functions.

"No such file or directory" with firebase_admin python library

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()

Python - Firebase DB reference error

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

Categories

Resources