### Setup Development Environment Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Create a virtual environment and install development dependencies. Ensure you have virtualenvwrapper installed for the mkvirtualenv command. ```bash mkvirtualenv -p python3 pyrebase-dev # if you have virtualenvwrapper installed pip install -r requirements.txt -r requirements.dev.txt ``` -------------------------------- ### Install Pyrebase4 Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Install the Pyrebase4 library using pip. ```shell pip install pyrebase4 ``` -------------------------------- ### Test Installation from Test PyPI Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Install the newly built version of pyrebase4 from the Test PyPI repository into a separate project to confirm it installs and functions correctly. Replace '[new version]' with the actual version number. ```bash pip install --index-url https://test.pypi.org/simple/ pyrebase4==[new version] ``` -------------------------------- ### Perform Complex Queries Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Chain multiple query parameters like `order_by_child()`, `limit_to_first()`, and `get()` to construct complex queries. This example retrieves the first three users ordered by name. ```python users_by_name = db.child("users").order_by_child("name").limit_to_first(3).get() ``` -------------------------------- ### Build Package Dependencies Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Install or update the necessary tools for building Python packages. This includes pip, setuptools, wheel, and twine. ```bash pip install --upgrade pip setuptools wheel twine ``` -------------------------------- ### Retrieve Data - get() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Fetch data from a specified path in the database. ```APIDOC #### get To return data from a path simply call the `get()` method. ```python all_users = db.child("users").get() ``` ``` -------------------------------- ### Get Account Information Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Retrieve the account information for the currently authenticated user. ```python # Get user info user = auth.get_account_info() ``` -------------------------------- ### Get All Records and Iterate Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves all records from a specified database path and allows iteration over each record. ```APIDOC ## Get all records and iterate all_users = db.child("users").get() for user in all_users.each(): print(user.key(), "->", user.val()) ``` -------------------------------- ### Get Data from a Path Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md The `get()` method is a fundamental way to retrieve data from a specified path in your Firebase database. It returns a PyreResponse object. ```python all_users = db.child("users").get() ``` -------------------------------- ### Get All Records and Iterate Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves all records from a database path and iterates through them. Useful for fetching all data at a specific location. ```python all_users = db.child("users").get() for user in all_users.each(): print(user.key(), "->", user.val()) ``` -------------------------------- ### Complex Queries - start_at() and end_at() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Define a range for query results by specifying the starting and ending values for a particular child property. ```APIDOC #### start_at and end_at Specify a range in your data. ```python users_by_score = db.child("users").order_by_child("score").start_at(3).end_at(10).get() ``` This query returns users ordered by score and with a score between 3 and 10. ``` -------------------------------- ### Retrieve Only Keys with shallow() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use the `shallow()` method followed by `get()` to retrieve only the keys at a specific path, without fetching the full data. This is efficient for getting a list of IDs or structure. ```python all_user_ids = db.child("users").shallow().get() ``` -------------------------------- ### Limit Data to First 5 Users by Score Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `limit_to_first()` to retrieve a specified number of records from the beginning of an ordered dataset. This example fetches the first 5 users sorted by their score. ```python users_by_score = db.child("users").order_by_child("score").limit_to_first(5).get() ``` -------------------------------- ### Shallow Get (Keys Only) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves only the keys from a database path without fetching the values. Useful for quickly listing available data. ```python keys = db.child("users").shallow().get() print(list(keys.val())) ``` -------------------------------- ### Get User Account Information with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves the full account profile for an authenticated user using their ID token. Requires prior authentication. ```python auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") info = auth.get_account_info(user["idToken"]) # { # "users": [{ # "localId": "abc123", # "email": "user@example.com", # "emailVerified": False, # "displayName": "Alice", # "createdAt": "1609459200000" # }] # } print(info["users"][0]["emailVerified"]) ``` -------------------------------- ### Shallow Get (Keys Only) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves only the keys from a specified database path without fetching the associated values. ```APIDOC ## Shallow get (keys only, no values) keys = db.child("users").shallow().get() print(list(keys.val())) ``` -------------------------------- ### Change User Email and Password with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Allows changing the email address or password for a currently authenticated user. Also includes an example for sending a password reset email without being signed in. ```python auth = firebase.auth() user = auth.sign_in_with_email_and_password("old@example.com", "password123") # Change email auth.change_email(user["idToken"], "new@example.com") # Change password auth.change_password(user["idToken"], "newSecurePassword456") # Send a password reset email without being signed in auth.send_password_reset_email("user@example.com") ``` -------------------------------- ### Retrieve Query Data with val() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Call the `val()` method on a PyreResponse object to get the actual data returned by a query. This is the primary way to access the content of your database nodes. ```python users = db.child("users").get() print(users.val()) # {"Morty": {"name": "Mortimer 'Morty' Smith"}, "Rick": {"name": "Rick Sanchez"}} ``` -------------------------------- ### Loop to Increment Value Conditionally Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md This example demonstrates a loop that repeatedly increments a numeric value using `conditional_set()`. It continues as long as the ETag is valid, ensuring atomicity. ```python etag = db.child("users").child("Morty").child("age").get_etag() while type(etag) is dict and "ETag" in etag: new_age = etag["value"] + 1 etag = db.child("users").child("Morty").child("age").conditional_set(new_age, etag["ETag"]) ``` -------------------------------- ### Complex Queries with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Demonstrates chaining query modifiers for filtering and sorting Firebase Realtime Database data. All queries must start with an `order_by_*` call. ```python top3 = db.child("users").order_by_child("score").limit_to_last(3).get() for u in top3.each(): print(u.key(), u.val()["score"]) ``` ```python mid_range = db.child("users").order_by_child("score").start_at(10).end_at(50).get() ``` ```python exact = db.child("users").order_by_child("score").equal_to(42).get() ``` ```python by_key = db.child("users").order_by_key().get() ``` ```python articles = db.child("articles").order_by_child("date").start_at(1700000000).end_at(1710000000).get() articles_by_likes = db.sort(articles, "likes", reverse=True) for a in articles_by_likes.each(): print(a.val()["title"], a.val()["likes"]) ``` -------------------------------- ### Retrieve Query Key with key() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use the `key()` method on a PyreResponse object to get the key (name) of the data node that the query targeted. This is useful for identifying the specific location of the data. ```python user = db.child("users").get() print(user.key()) # users ``` -------------------------------- ### Retrieve Data - shallow() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Retrieve only the keys at a particular path, useful for getting a list of IDs without fetching the full data. Cannot be used with complex queries. ```APIDOC #### shallow To return just the keys at a particular path use the `shallow()` method. ```python all_user_ids = db.child("users").shallow().get() ``` Note: `shallow()` can not be used in conjunction with any complex queries. ``` -------------------------------- ### Handle Conditional Request Response Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Conditional requests return a dictionary with a new ETag if the condition fails (ETag mismatch). If successful, they return nothing or a success indicator. This example shows how to check the response. ```python { "ETag": "8KnE63B6HiKp67Wf3HQrXanujSM=", "value": "" } ``` ```python etag = db.child("users").child("Morty").get_etag() response = db.child("users").child("Morty").conditional_remove(etag["ETag"]) if type(response) is dict and "ETag" in response: etag = response["ETag"] # our ETag was out-of-date else: print("We removed the data successfully!") ``` -------------------------------- ### Get Public Download URL for a File Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves a publicly accessible URL for a file stored in Firebase Storage. An `idToken` is required for authenticated files; use `None` for publicly readable files. ```python storage = firebase.storage() auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") url = storage.child("images/profile.jpg").get_url(user["idToken"]) print(url) # https://firebasestorage.googleapis.com/v0/b/my-project.appspot.com/o/images%2Fprofile.jpg?alt=media&token=... # Public URL without token (for publicly readable files) public_url = storage.child("public/banner.png").get_url(None) ``` -------------------------------- ### Configure Test Database Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Copy the service account key and configuration template to set up the test database. Update the config.py file with your specific test database details. ```bash cp ~/my_secret_firebase_service_account_key.json ./secret.json cp ./tests/config.template.py ./tests/config.py # Update the ./tests/config.py file with your test database. ``` -------------------------------- ### Initialize Pyrebase App with Basic Configuration Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Initialize the Pyrebase app with essential configuration parameters for user-based authentication. ```python import pyrebase config = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com" } firebase = pyrebase.initialize_app(config) ``` -------------------------------- ### Upload to Test PyPI Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Upload the built package files to the Test PyPI repository for initial verification. This step requires authentication with your Test PyPI credentials. ```bash twine upload --repository-url https://test.pypi.org/legacy/ dist/* ``` -------------------------------- ### Initialize Pyrebase App with Service Account Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Initialize the Pyrebase app with a service account credential for server-side authentication and bypassing security rules. ```python import pyrebase config = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com", "serviceAccount": "path/to/serviceAccountCredentials.json" } firebase = pyrebase.initialize_app(config) ``` -------------------------------- ### Create Distribution Files Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Generate the source distribution (sdist) and wheel (bdist_wheel) files for the pyrebase4 package. Ensure the version number in setup.py is incremented and the dist/ directory is clean. ```bash python setup.py sdist bdist_wheel ``` -------------------------------- ### Create Storage Path Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `child()` with the Storage service to construct paths to files. This method is analogous to building paths in the database service. ```python storage.child("images/example.jpg") ``` -------------------------------- ### Initialize Firebase App Source: https://context7.com/nhorvath/pyrebase4/llms.txt Initialize a Firebase app instance with configuration. Supports both user-level and admin-level access. ```python import pyrebase # User-level access config = { "apiKey": "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXX", "authDomain": "my-project.firebaseapp.com", "databaseURL": "https://my-project-default-rtdb.firebaseio.com", "storageBucket": "my-project.appspot.com" } firebase = pyrebase.initialize_app(config) # Admin access with service account config_admin = { "apiKey": "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXX", "authDomain": "my-project.firebaseapp.com", "databaseURL": "https://my-project-default-rtdb.firebaseio.com", "storageBucket": "my-project.appspot.com", "serviceAccount": "path/to/serviceAccountCredentials.json" # or pass a dict: "serviceAccount": {"type": "service_account", ...} } firebase_admin = pyrebase.initialize_app(config_admin) # Access services auth = firebase.auth() db = firebase.database() storage = firebase.storage() ``` -------------------------------- ### Initialize Firebase App Source: https://context7.com/nhorvath/pyrebase4/llms.txt Initializes a Firebase app instance using provided configuration. Supports both user-level and admin-level access. ```APIDOC ## initialize_app(config) ### Description Initializes a Firebase app instance with the provided configuration dictionary. This function can be used for both user-level authentication and admin-level access using service account credentials. ### Parameters - **config** (dict) - Required - A dictionary containing Firebase project credentials like `apiKey`, `authDomain`, `databaseURL`, `storageBucket`. Can optionally include `serviceAccount` for admin access. ### Request Example ```python import pyrebase # User-level access configuration config = { "apiKey": "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXX", "authDomain": "my-project.firebaseapp.com", "databaseURL": "https://my-project-default-rtdb.firebaseio.com", "storageBucket": "my-project.appspot.com" } firebase = pyrebase.initialize_app(config) # Admin access configuration config_admin = { "apiKey": "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXX", "authDomain": "my-project.firebaseapp.com", "databaseURL": "https://my-project-default-rtdb.firebaseio.com", "storageBucket": "my-project.appspot.com", "serviceAccount": "path/to/serviceAccountCredentials.json" } firebase_admin = pyrebase.initialize_app(config_admin) # Access services auth = firebase.auth() db = firebase.database() storage = firebase.storage() ``` ``` -------------------------------- ### Sign In with Email and Password Source: https://context7.com/nhorvath/pyrebase4/llms.txt Authenticates an existing user with their email and password, returning session tokens. ```APIDOC ## auth.sign_in_with_email_and_password(email, password) ### Description Authenticates an existing user by verifying their email and password. Upon successful authentication, it returns a user object containing session tokens and user information. ### Parameters - **email** (string) - Required - The user's registered email address. - **password** (string) - Required - The user's password. ### Request Example ```python auth = firebase.auth() try: user = auth.sign_in_with_email_and_password("user@example.com", "password123") print(user["idToken"]) print(user["refreshToken"]) print(user["localId"]) # Example of refreshing the token user = auth.refresh(user["refreshToken"]) fresh_token = user["idToken"] except HTTPError as e: print(f"Login failed: {e}") ``` ### Response #### Success Response (200) - **idToken** (string) - JWT token for authenticated requests. Valid for 1 hour. - **refreshToken** (string) - Token used to obtain a new `idToken` before expiry. - **localId** (string) - The Firebase UID of the authenticated user. #### Error Response - **error** (object) - Contains details about the login failure. ``` -------------------------------- ### Helper Methods Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Utility methods for generating keys and sorting data. ```APIDOC ## generate_key ### Description Generates a unique key using Firebase's algorithm, suitable for multi-location updates. ### Method `generate_key()` ### Request Example ```python db.generate_key() ``` ``` -------------------------------- ### Get Storage File URL Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md The `get_url()` method retrieves a publicly accessible URL for a file stored in Firebase Storage. A user token is required for authentication. ```python storage.child("images/example.jpg").get_url(user["idToken"]) # https://firebasestorage.googleapis.com/v0/b/storage-url.appspot.com/o/images%2Fexample.jpg?alt=media ``` -------------------------------- ### Sign In with Custom Token Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Sign in a user using a previously generated custom token. This can be done on the client or server. ```python user = auth.sign_in_with_custom_token(token) ``` -------------------------------- ### Initialize Pyrebase App Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Initialize the Pyrebase app with your Firebase configuration. You can optionally include service account credentials for server-side authentication. ```APIDOC ## Initialize Pyrebase App ### Description Initialize the Pyrebase app with your Firebase configuration. You can optionally include service account credentials for server-side authentication. ### Code Example ```python import pyrebase config = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com" } firbase = pyrebase.initialize_app(config) # With service account config_with_sa = { "apiKey": "apiKey", "authDomain": "projectId.firebaseapp.com", "databaseURL": "https://databaseName.firebaseio.com", "storageBucket": "projectId.appspot.com", "serviceAccount": "path/to/serviceAccountCredentials.json" } firbase_sa = pyrebase.initialize_app(config_with_sa) ``` ``` -------------------------------- ### Upload to Main PyPI Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Upload the final, verified package files to the main Python Package Index (PyPI). This makes the pyrebase4 package publicly available. ```bash twine upload dist/* ``` -------------------------------- ### Sign In with Email and Password Source: https://context7.com/nhorvath/pyrebase4/llms.txt Authenticate an existing user and retrieve user credentials. The idToken expires after 1 hour and can be refreshed using the refreshToken. ```python auth = firebase.auth() try: user = auth.sign_in_with_email_and_password("user@example.com", "password123") print(user["idToken"]) print(user["refreshToken"]) print(user["localId"]) # Refresh token before 1-hour expiry user = auth.refresh(user["refreshToken"]) fresh_token = user["idToken"] except HTTPError as e: print(f"Login failed: {e}") ``` -------------------------------- ### db.child(*args) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Builds a database path by chaining path segments to target a specific location. ```APIDOC ## db.child(*args) ### Description Chains path segments to target a specific database location. All read/write operations are relative to the path built with `child()`. ### Parameters #### Path Parameters - **args** (string) - Required - One or more path segments to build the database reference. ### Request Example ```python db = firebase.database() # Equivalent paths ref = db.child("users").child("alice") ref = db.child("users", "alice") # multi-segment shorthand ``` ``` -------------------------------- ### Authenticate User with Email and Password Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Log in a user using their email and password. This method returns user data including an idToken. ```python # Get a reference to the auth service auth = firebase.auth() # Log the user in user = auth.sign_in_with_email_and_password(email, password) ``` -------------------------------- ### db.get(token) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Reads data from a specified path and returns a PyreResponse object. ```APIDOC ## db.get(token) ### Description Retrieves data and returns a `PyreResponse` object. Call `.val()` for the raw data, `.key()` for the path key, and `.each()` to iterate over child nodes. ### Parameters #### Path Parameters - **token** (string) - Optional - The authentication token for authenticated reads. ### Request Example ```python db = firebase.database() # Get a single record user_data = db.child("users").child("alice").get() print(user_data.val()) # {"name": "Alice", "score": 99} print(user_data.key()) # "alice" ``` ### Response #### Success Response (200) - **val()** - Returns the raw data at the path. - **key()** - Returns the key of the current node. - **each()** - Returns an iterator for child nodes. ``` -------------------------------- ### Build Database Path with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Chains path segments to target a specific database location. All read/write operations are relative to the path built with `child()`. Supports multi-segment shorthand. ```python db = firebase.database() # Equivalent paths ref = db.child("users").child("alice") ref = db.child("users", "alice") ``` -------------------------------- ### Order Data by Key Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `order_by_key()` to sort data in ascending order based on its keys. This is useful for retrieving data in a predictable order when keys are meaningful. ```python users_by_key = db.child("users").order_by_key().get() ``` -------------------------------- ### Sign In Anonymously Source: https://context7.com/nhorvath/pyrebase4/llms.txt Create an anonymous user session for limited access without registration. The returned idToken can be used for authenticated requests. ```python auth = firebase.auth() user = auth.sign_in_anonymous() print(user["idToken"]) print(user["localId"]) ``` -------------------------------- ### Run Tests Source: https://github.com/nhorvath/pyrebase4/blob/master/DEV.md Execute the test suite using pytest. The tests interact with a Firebase database path named '/pyrebase_tests/'. On MacOS, you might need to adjust the pytest executable's shebang. ```bash pytest -s tests ``` -------------------------------- ### Register New User Source: https://context7.com/nhorvath/pyrebase4/llms.txt Create a new Firebase user with email and password. Requires the Email/Password provider to be enabled in Firebase console. Handles potential HTTP errors during registration. ```python from requests.exceptions import HTTPError auth = firebase.auth() try: user = auth.create_user_with_email_and_password("newuser@example.com", "securepassword123") print(user["localId"]) print(user["idToken"]) print(user["email"]) # Send verification email after registration auth.send_email_verification(user["idToken"]) except HTTPError as e: print(f"Registration failed: {e}") ``` -------------------------------- ### Create Custom Token with Additional Claims Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Generate a custom authentication token with additional custom claims, such as 'premium_account', which can be used for fine-grained access control. ```python token_with_additional_claims = auth.create_custom_token("your_custom_id", {"premium_account": True}) ``` -------------------------------- ### Create User with Email and Password Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Create a new user account using an email address and password. Ensure the Email/password provider is enabled in your Firebase dashboard. ```python auth.create_user_with_email_and_password(email, password) ``` -------------------------------- ### Save Data with Custom Key Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Save data to the database using the set method, allowing you to define your own keys for the data entries. This overwrites existing data at the specified path. ```python data = {"name": "Mortimer 'Morty' Smith"} db.child("users").child("Morty").set(data) ``` -------------------------------- ### Authentication Methods Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Methods for user authentication, including email/password sign-in, anonymous sign-in, profile updates, account info retrieval, and token management. ```APIDOC ## Authentication Methods ### Description Methods for user authentication, including email/password sign-in, anonymous sign-in, profile updates, account info retrieval, and token management. ### Methods #### Sign in with email and password ```python auth.sign_in_with_email_and_password(email, password) ``` #### Sign in anonymously ```python auth.sign_in_anonymous() ``` #### Update user profile ```python auth.update_profile(display_name, photo_url, delete_attribute) ``` #### Get account information ```python auth.get_account_info() ``` #### Refresh token ```python user = auth.refresh(user['refreshToken']) ``` #### Create custom token ```python token = auth.create_custom_token("your_custom_id") token_with_additional_claims = auth.create_custom_token("your_custom_id", {"premium_account": True}) ``` #### Sign in with custom token ```python user = auth.sign_in_with_custom_token(token) ``` #### Create user with email and password ```python auth.create_user_with_email_and_password(email, password) ``` #### Send email verification ```python auth.send_email_verification(user['idToken']) ``` #### Send password reset email ```python auth.send_password_reset_email("email") ``` #### Delete user account ```python auth.delete_user_account(user['idToken']) ``` ``` -------------------------------- ### db.set(data, token) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Writes (overwrites) data at an exact path, using a specific key. ```APIDOC ## db.set(data, token) ### Description Writes (overwrites) data at an exact path. Use `.child("key")` to define the key explicitly. ### Parameters #### Path Parameters - **data** (object) - Required - The data to write. - **token** (string) - Optional - The authentication token for authenticated writes. ### Request Example ```python db = firebase.database() data = {"name": "Alice", "score": 42, "active": True} # Set with a known key db.child("users").child("alice").set(data) # Overwrite a nested field db.child("users").child("alice").child("score").set(100) ``` ``` -------------------------------- ### Save Data to Database with Auto-Generated Key Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Save data to the database using the push method, which generates a unique, timestamp-based key for the new entry. Requires user authentication for security rules. ```python # Get a reference to the database service db = firebase.database() # data to save data = { "name": "Mortimer 'Morty' Smith" } # Pass the user's idToken to the push method results = db.child("users").push(data, user['idToken']) ``` -------------------------------- ### Read Data from Realtime Database with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves data from a specified path and returns a `PyreResponse` object. Use `.val()` for raw data, `.key()` for the path key, and `.each()` to iterate over child nodes. ```python db = firebase.database() # Get a single record user_data = db.child("users").child("alice").get() print(user_data.val()) # {"name": "Alice", "score": 99} print(user_data.key()) # "alice" ``` -------------------------------- ### storage.child(*args).get_url(token) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Returns a publicly accessible download URL for a stored file. A token is required for authenticated access, but can be None for publicly readable files. ```APIDOC ## `storage.child(*args).get_url(token)` — Get a public download URL Returns a publicly accessible download URL for a stored file. ```python storage = firebase.storage() auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") url = storage.child("images/profile.jpg").get_url(user["idToken"]) print(url) # https://firebasestorage.googleapis.com/v0/b/my-project.appspot.com/o/images%2Fprofile.jpg?alt=media&token=... # Public URL without token (for publicly readable files) public_url = storage.child("public/banner.png").get_url(None) ``` ``` -------------------------------- ### Real-time Data Streaming with SSE Source: https://context7.com/nhorvath/pyrebase4/llms.txt Listens to live changes at a database path using Server-Sent Events (SSE). The `stream_handler` callback processes incoming messages. Runs asynchronously by default. ```python def handle_message(message): print("Event:", message["event"]) # "put" or "patch" print("Path:", message["path"]) # "/new_key" or "/-NxKEY..." print("Data:", message["data"]) ``` ```python stream = db.child("posts").stream(handle_message, stream_id="posts_stream") ``` ```python auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") auth_stream = db.child("private").stream(handle_message, token=user["idToken"]) ``` ```python import time time.sleep(10) stream.close() ``` -------------------------------- ### Retrieve Data - each() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Iterate over the query results, allowing access to both the key and value of each item. Each item in the iteration is a PyreResponse object. ```APIDOC #### each Returns a list of objects on each of which you can call `val()` and `key()`. ``` all_users = db.child("users").get() for user in all_users.each(): print(user.key()) # Morty print(user.val()) # {"name": "Mortimer 'Morty' Smith"} ``` ``` -------------------------------- ### Download File from Storage Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `download()` to retrieve a file from Firebase Storage. Specify the storage path and the desired local filename for the downloaded file. ```python storage.child("images/example.jpg").download("downloaded.jpg") ``` -------------------------------- ### Build Database Path Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Construct a reference to a specific location in the Firebase database using the child() method to navigate through the data structure. ```python db = firebase.database() db.child("users").child("Morty") ``` -------------------------------- ### Create Custom JWT Token Source: https://context7.com/nhorvath/pyrebase4/llms.txt Generate a signed JWT for a given UID, optionally embedding custom claims and setting an expiry time. Requires service account credentials for initialization. ```python # firebase must be initialized with serviceAccount credentials auth = firebase_admin.auth() # Basic custom token token = auth.create_custom_token("user_custom_id_42") # With additional claims and custom expiry token = auth.create_custom_token( "user_custom_id_42", additional_claims={"premium_account": True, "role": "editor"}, expiry_minutes=120 ) # Sign in on the server using the custom token user = auth.sign_in_with_custom_token(token) print(user["idToken"]) ``` -------------------------------- ### storage.list_files() Source: https://context7.com/nhorvath/pyrebase4/llms.txt Returns an iterator of all blob objects in the storage bucket. This operation requires service account credentials. ```APIDOC ## `storage.list_files()` — List all files in a bucket Returns an iterator of all blob objects in the storage bucket. Requires service account credentials. ```python # firebase must be initialized with serviceAccount credentials storage = firebase_admin.storage() blobs = storage.list_files() for blob in blobs: print(blob.name, blob.size, blob.updated) # images/profile.jpg 45230 2024-01-15T10:30:00Z # uploads/report.pdf 102400 2024-01-16T08:00:00Z ``` ``` -------------------------------- ### Create Custom Token Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Generate a custom authentication token for a user. This token can be used for server-side authentication or to sign in users on the client. ```python token = auth.create_custom_token("your_custom_id") ``` -------------------------------- ### Stream Live Data Changes Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md The `stream()` method allows you to listen for real-time updates to your data. A handler function is called for each change event (e.g., 'put', 'patch'). ```python def stream_handler(message): print(message["event"]) # put print(message["path"]) # /-K7yGTTEp7O549EzTYtI print(message["data"]) # {'title': 'Pyrebase', "body": "etc..."} my_stream = db.child("posts").stream(stream_handler) ``` ```python my_stream = db.child("posts").stream(stream_handler, stream_id="new_posts") ``` -------------------------------- ### Create User with Email and Password Source: https://context7.com/nhorvath/pyrebase4/llms.txt Registers a new user in Firebase using their email and password. Requires the Email/Password sign-in provider to be enabled. ```APIDOC ## auth.create_user_with_email_and_password(email, password) ### Description Creates a new Firebase user account using the provided email address and password. This method requires the Email/Password authentication provider to be enabled in your Firebase project settings. ### Parameters - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's desired password. ### Request Example ```python from requests.exceptions import HTTPError auth = firebase.auth() try: user = auth.create_user_with_email_and_password("newuser@example.com", "securepassword123") print(user["localId"]) print(user["idToken"]) print(user["email"]) auth.send_email_verification(user["idToken"]) except HTTPError as e: print(f"Registration failed: {e}") ``` ### Response #### Success Response (200) - **localId** (string) - The unique identifier for the newly created user. - **idToken** (string) - A JWT token for authenticating subsequent requests. Valid for 1 hour. - **email** (string) - The email address of the registered user. #### Error Response - **error** (object) - Contains details about the error if registration fails. ``` -------------------------------- ### List All Files in Storage Bucket Source: https://context7.com/nhorvath/pyrebase4/llms.txt Lists all blob objects within the Firebase Storage bucket. This operation requires service account credentials for initialization. ```python # firebase must be initialized with serviceAccount credentials storage = firebase_admin.storage() blobs = storage.list_files() for blob in blobs: print(blob.name, blob.size, blob.updated) # images/profile.jpg 45230 2024-01-15T10:30:00Z # uploads/report.pdf 102400 2024-01-16T08:00:00Z ``` -------------------------------- ### Real-time Data Streaming Source: https://context7.com/nhorvath/pyrebase4/llms.txt Listens to live changes at a database path using Server-Sent Events (SSE). The `stream_handler` callback receives messages with `event`, `path`, and `data` fields. ```APIDOC ## `db.stream(stream_handler, token, stream_id, is_async)` — Real-time data streaming Listens to live changes at a database path via SSE. The `stream_handler` callback receives messages with `event`, `path`, and `data` fields. Runs on a background thread by default (`is_async=True`). ```python db = firebase.database() def handle_message(message): print("Event:", message["event"]) print("Path:", message["path"]) print("Data:", message["data"]) # Start streaming (non-blocking, runs on a background thread) stream = db.child("posts").stream(handle_message, stream_id="posts_stream") # With user authentication auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") auth_stream = db.child("private").stream(handle_message, token=user["idToken"]) # Stop the stream when done import time time.sleep(10) stream.close() ``` ``` -------------------------------- ### Authenticate User Anonymously Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Log in a user anonymously. This is useful for providing basic access without requiring user credentials. ```python # Log the user in anonymously user = auth.sign_in_anonymous() ``` -------------------------------- ### Conditional Requests with ETags Source: https://context7.com/nhorvath/pyrebase4/llms.txt Implements optimistic concurrency control using ETags for writes and deletes. Operations only succeed if the ETag matches the current server value. ```python result = db.child("users").child("alice").child("score").get_etag() current_score = result["value"] # e.g., 42 etag = result["ETag"] # e.g., "8KnE63B6HiKp67Wf3HQrXanujSM=" ``` ```python while True: new_score = result["value"] + 1 result = db.child("users").child("alice").child("score").conditional_set(new_score, result["ETag"]) if not (isinstance(result, dict) and "ETag" in result): print("Score updated to", new_score) break # success # ETag mismatch: result contains new ETag and current value; retry ``` ```python etag_info = db.child("users").child("alice").get_etag() response = db.child("users").child("alice").conditional_remove(etag_info["ETag"]) if isinstance(response, dict) and "ETag" in response: print("Conflict — node was modified, new ETag:", response["ETag"]) else: print("Deleted successfully") ``` -------------------------------- ### auth.get_account_info(id_token) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Retrieves the full account profile for the authenticated user using their ID token. ```APIDOC ## auth.get_account_info(id_token) ### Description Retrieves the full account profile for the authenticated user. ### Parameters #### Path Parameters - **id_token** (string) - Required - The ID token of the authenticated user. ### Request Example ```python auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") info = auth.get_account_info(user["idToken"]) ``` ### Response #### Success Response (200) - **users** (list) - A list of user objects, each containing account details like localId, email, displayName, etc. ### Response Example ```json { "users": [{ "localId": "abc123", "email": "user@example.com", "emailVerified": false, "displayName": "Alice", "createdAt": "1609459200000" }] } ``` ``` -------------------------------- ### Sign In Anonymously Source: https://context7.com/nhorvath/pyrebase4/llms.txt Creates an anonymous user session, useful for granting limited access without requiring user registration. ```APIDOC ## auth.sign_in_anonymous() ### Description Creates a new anonymous user session. This is useful for providing access to certain features or data without requiring users to register an account. ### Request Example ```python auth = firebase.auth() user = auth.sign_in_anonymous() print(user["idToken"]) print(user["localId"]) ``` ### Response #### Success Response (200) - **idToken** (string) - A JWT token that can be used for authenticated requests on behalf of the anonymous user. - **localId** (string) - The unique identifier for the anonymous user. ``` -------------------------------- ### Conditional Requests Source: https://context7.com/nhorvath/pyrebase4/llms.txt Implements optimistic concurrency control using ETags for conditional writes and deletes. A write/delete only succeeds if the ETag matches the current server value. ```APIDOC ## `db.get_etag(token)` / `db.conditional_set(data, etag, token)` / `db.conditional_remove(etag, token)` — Conditional requests Implements optimistic concurrency control using ETags. A write/delete only succeeds if the ETag matches the current server value; on conflict, the updated ETag and current value are returned. ```python db = firebase.database() # Read current value and ETag result = db.child("users").child("alice").child("score").get_etag() current_score = result["value"] # e.g., 42 etag = result["ETag"] # e.g., "8KnE63B6HiKp67Wf3HQrXanujSM=" # Conditional increment (retry loop for concurrent updates) while True: new_score = result["value"] + 1 result = db.child("users").child("alice").child("score").conditional_set(new_score, result["ETag"]) if not (isinstance(result, dict) and "ETag" in result): print("Score updated to", new_score) break # success # ETag mismatch: result contains new ETag and current value; retry # Conditional delete etag_info = db.child("users").child("alice").get_etag() response = db.child("users").child("alice").conditional_remove(etag_info["ETag"]) if isinstance(response, dict) and "ETag" in response: print("Conflict — node was modified, new ETag:", response["ETag"]) else: print("Deleted successfully") ``` ``` -------------------------------- ### Complex Queries - order_by_child() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Begin a complex query by ordering the results based on the value of a specified child property. ```APIDOC ### Complex Queries Queries can be built by chaining multiple query parameters together. ```python users_by_name = db.child("users").order_by_child("name").limit_to_first(3).get() ``` This query will return the first three users ordered by name. #### order_by_child We begin any complex query with `order_by_child()`. ```python users_by_name = db.child("users").order_by_child("name").get() ``` This query will return users ordered by name. ``` -------------------------------- ### Streaming Data - stream() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Listen for live changes to data at a specific path. The `stream()` method takes a handler function that processes incoming messages. ```APIDOC #### streaming You can listen to live changes to your data with the `stream()` method. ```python def stream_handler(message): print(message["event"]) print(message["path"]) print(message["data"]) my_stream = db.child("posts").stream(stream_handler) ``` You should at least handle `put` and `patch` events. Refer to ["Streaming from the REST API"](https://firebase.google.com/docs/reference/rest/database/#section-streaming) for details. You can also add a `stream_id` to help you identify a stream if you have multiple running: ``` my_stream = db.child("posts").stream(stream_handler, stream_id="new_posts") ``` ``` -------------------------------- ### Complex Queries Source: https://context7.com/nhorvath/pyrebase4/llms.txt Demonstrates chaining query modifiers like `order_by_child`, `start_at`, `end_at`, `equal_to`, `limit_to_first`, `limit_to_last`, `order_by_key`, and `order_by_value` for filtering and sorting data. ```APIDOC ## Complex Queries — `order_by_child`, `start_at`, `end_at`, `equal_to`, `limit_to_first`, `limit_to_last`, `order_by_key`, `order_by_value` Chainable query modifiers for filtering and sorting Firebase Realtime Database data. All queries must begin with an `order_by_*` call. ```python db = firebase.database() # Top 3 users by score (ascending) top3 = db.child("users").order_by_child("score").limit_to_last(3).get() for u in top3.each(): print(u.key(), u.val()["score"]) # Users with score between 10 and 50 mid_range = db.child("users").order_by_child("score").start_at(10).end_at(50).get() # Users with exactly score=42 exact = db.child("users").order_by_child("score").equal_to(42).get() # All users sorted by their Firebase-generated key by_key = db.child("users").order_by_key().get() # Sort a local result set by a secondary field articles = db.child("articles").order_by_child("date").start_at(1700000000).end_at(1710000000).get() articles_by_likes = db.sort(articles, "likes", reverse=True) for a in articles_by_likes.each(): print(a.val()["title"], a.val()["likes"]) ``` ``` -------------------------------- ### Iterate Through Each Item with each() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md The `each()` method returns a list of objects, allowing you to iterate through child nodes. Each object in the list has `key()` and `val()` methods to access its key and data. ```python all_users = db.child("users").get() for user in all_users.each(): print(user.key()) # Morty print(user.val()) # {"name": "Mortimer 'Morty' Smith"} ``` -------------------------------- ### Order Data by Child Property Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `order_by_child()` to sort your data based on the value of a specific child property. This is often the first step in building more complex queries. ```python users_by_name = db.child("users").order_by_child("name").get() ``` -------------------------------- ### Download File from Firebase Storage Source: https://context7.com/nhorvath/pyrebase4/llms.txt Downloads a file from Firebase Storage to a specified local path. Use an `idToken` for authenticated user downloads or omit for admin downloads. ```python storage = firebase.storage() auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") # Download as admin (service account) storage.child("images/profile.jpg").download("images/profile.jpg", "downloaded_profile.jpg") # Download as authenticated user storage.child("uploads/report.pdf").download("uploads/report.pdf", "local_report.pdf", token=user["idToken"]) ``` -------------------------------- ### Filter Data Within a Range Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `start_at()` and `end_at()` together with `order_by_child()` to retrieve data within a specified numerical range for a child property. ```python users_by_score = db.child("users").order_by_child("score").start_at(3).end_at(10).get() ``` -------------------------------- ### Partial Update or Multi-Location Write with Pyrebase Source: https://context7.com/nhorvath/pyrebase4/llms.txt Merges new data into an existing record without overwriting other fields. Also supports multi-location atomic writes from the database root and multi-location writes with generated keys. ```python db = firebase.database() # Partial update — only "score" is changed; other fields are preserved db.child("users").child("alice").update({"score": 99}) # Multi-location atomic update from root db.update({ "users/alice/score": 99, "leaderboard/alice": 99 }) # Multi-location write with generated keys db.update({ "posts/" + db.generate_key(): {"title": "Post A", "author": "alice"}, "posts/" + db.generate_key(): {"title": "Post B", "author": "bob"} }) ``` -------------------------------- ### Retrieve Data - key() Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Retrieve the key associated with the query data. The `key()` method is called on a PyreResponse object. ```APIDOC #### key Calling `key()` returns the key for the query data. ``` user = db.child("users").get() print(user.key()) # users ``` ``` -------------------------------- ### Order Data by Value Source: https://github.com/nhorvath/pyrebase4/blob/master/README.md Use `order_by_value()` to sort data based on the values of its children. This is applicable when the direct values of nodes are comparable. ```python users_by_value = db.child("users").order_by_value().get() ``` -------------------------------- ### storage.child(*args).download(path, filename, token) Source: https://context7.com/nhorvath/pyrebase4/llms.txt Downloads a file from Firebase Storage to a local path. Can be used with an authenticated user's token or for admin downloads. ```APIDOC ## `storage.child(*args).download(path, filename, token)` — Download a file Downloads a file from Firebase Storage to a local path. ```python storage = firebase.storage() auth = firebase.auth() user = auth.sign_in_with_email_and_password("user@example.com", "password123") # Download as admin (service account) storage.child("images/profile.jpg").download("images/profile.jpg", "downloaded_profile.jpg") # Download as authenticated user storage.child("uploads/report.pdf").download("uploads/report.pdf", "local_report.pdf", token=user["idToken"]) ``` ```