Firebase Realtime Database is a cloud-hosted NoSQL database that allows you to store and sync data between your users in real-time. You can use the Firebase Realtime Database with Python using the firebase-admin
library. Here is an example of how to send a message to the Firebase Realtime Database using Python:
- Install the firebase-admin library:
pip install firebase-admin
- Import the necessary modules:
from firebase_admin import credentials, db
- Initialize the Firebase Admin SDK with a service account:
cred = credentials.Certificate('path/to/serviceAccountKey.json') firebase_admin.initialize_app(cred, {'databaseURL': 'https://your-project-name.firebaseio.com'})
- Get a reference to the database:
ref = db.reference()
- Send a message to the database:
ref.child("messages").push({"text": "Hello, World!"})
- You can also listen for real-time updates to the database:
def on_message(event): print(event.event_type) # can be 'put' or 'patch' print(event.path) print(event.data) # new data at /path my_stream = ref.child("messages").stream(on_message)
Make sure to replace "path/to/serviceAccountKey.json" with the path to your service account key and "your-project-name" with the name of your Firebase project. The file will have the following structure:
{ "type": "service_account", "project_id": "your-project-id", "private_key_id": "your-private-key-id", "private_key": "-----BEGIN PRIVATE KEY-----\nyour-private-key\n-----END PRIVATE KEY-----\n", "client_email": "your-service-account-email", "client_id": "your-client-id", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your-service-account-email" }
Also, you can use the python library pyrebase
to interact with the Firebase Realtime Database using the REST API, it has some more functionality than firebase-admin
library.
Top comments (0)