Pyrebase4

repository·master·Indexed 43 days ago

https://github.com/nhorvath/pyrebase4

A simple Python wrapper for the Firebase API providing access to Authentication, Realtime Database, and Cloud Storage services. It supports user management, complex database queries with conditional requests, and file operations. Requires Python 3.

Tokens
3.3K
Snippets
16
Records
19
Agent score
5%

What's inside Pyrebase4

  1. Access Firebase services

    master

    A Pyrebase app provides access to different Firebase services through the main app instance:

    • firebase.auth(): Authentication service
    • firebase.database(): Realtime Database service
    • firebase.storage(): Cloud Storage service
  2. Use Conditional Requests in the Database

    master

    To prevent overwriting data if it has changed since you last read it, use conditional requests. This requires an ETag.

    1. Get the ETag using get_etag().
    2. Use conditional_set(data, etag) or conditional_remove(etag).

    If the ETag does not match, the method returns a dictionary containing the current ETag and value instead of performing the operation.

    etag = db.child("users").child("Morty").get_etag()
    data = {"name": "Mortimer 'Morty' Smith"}
    # This will only succeed if the ETag matches
    db.child("users").child("Morty").conditional_set(data, etag["ETag"])
  3. Initialize Pyrebase4 with configuration

    master

    To use Pyrebase4, initialize the app with a configuration dictionary containing your Firebase project credentials.

    Note: Pyrebase4 requires Python 3 and is not compatible with Python 2.

    import pyrebase
    
    config = {
      "apiKey": "apiKey",
      "authDomain": "projectId.firebaseapp.com",
      "databaseURL": "https://databaseName.firebaseio.com",
      "storageBucket": "projectId.appspot.com"
    }
    
    firebase = pyrebase.initialize_app(config)
  4. Set up a development environment for Pyrebase4

    master

    To develop on Pyrebase4, create a new virtual environment using Python 3 and install both the core requirements and the development-specific dependencies.

    If you use virtualenvwrapper, you can use mkvirtualenv. Otherwise, use standard venv tools to create a Python 3 environment.

    mkvirtualenv -p python3 pyrebase-dev
    pip install -r requirements.txt -r requirements.dev.txt
  5. Perform Database operations

    master

    Use firebase.database() to interact with the Realtime Database. You can build paths using the .child() method.

    Writing Data

    • push(data, [token]): Saves data with a unique, timestamp-based key.
    • set(data): Saves data at a specific key (e.g., .child("Morty").set(data)).
    • update(data, [token]): Updates existing entries. Can also perform multi-location updates by passing a dictionary of paths.
    • remove([token]): Deletes data at the specified path.

    Reading Data

    • get([token]): Returns a PyreResponse object.
    • val(): Called on a PyreResponse to get the actual data.
    • key(): Returns the key of the query result.
    • each(): Iterates over children, returning objects that support .val() and .key().
    • shallow(): Returns only the keys at a path (cannot be used with complex queries).
    db = firebase.database()
    
    # Push data
    db.child("users").push({"name": "Morty"})
    
    # Set data at specific key
    db.child("users").child("Morty").set({"name": "Morty"})
    
    # Get data
    users = db.child("users").get()
    print(users.val())
  6. Build and release Pyrebase4 to PyPI

    master

    To release a new version of Pyrebase4, follow these steps:

    1. Prepare dependencies: Upgrade pip, setuptools, wheel, and twine.
    2. Version Bump: Increment the version number in setup.py.
    3. Clean: Remove the existing dist/ directory.
    4. Package: Generate source and wheel distributions.
    5. Test Upload: Upload to Test PyPI to verify the package.
    6. Verify: Install the package from Test PyPI in a separate project to ensure it works.
    7. Final Upload: Upload the package to the main PyPI repository.

    Note: Registration for https://test.pypi.org is separate from https://pypi.org.

    # 1. Install/Update build dependencies
    pip install --upgrade pip setuptools wheel twine
    
    # 2. Increment the version number in setup.py
    
    # 3. Clean the dist/ directory
    
    # 4. Create the package files
    python setup.py sdist bdist_wheel
    
    # 5. Upload to test pypi repo
    twine upload --repository-url https://test.pypi.org/legacy/ dist/*
    
    # 6. Check that package installs and works in another project
    pip install --index-url https://test.pypi.org/simple/ pyrebase4==[new version]
    
    # 7. Upload to main pypi repo
    twine upload dist/*
  7. Configure a test database for development

    master

    Before running tests, you must configure a Firebase test database. This involves setting up your service account key and initializing the test configuration file.

    Important: The test suite is designed to read and write to the /pyrebase_tests/ path on your Firebase database to avoid interfering with other data. Ensure your tests/config.py is correctly pointed to your test database instance.

    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.
  8. Authenticate users with the Auth service

    master

    Use the auth service to manage user sessions. Methods like sign_in_with_email_and_password() return a user object containing an idToken. This token is required to adhere to Firebase security rules when performing database or storage operations.

    Token Expiry: The idToken expires after 1 hour. Use the refreshToken with the refresh() method to obtain a new token without requiring the user to re-authenticate.

    # Get a reference to the auth service
    auth = firebase.auth()
    
    # Log the user in
    user = auth.sign_in_with_email_and_password(email, password)
    
    # Refresh token before 1 hour expiry
    user = auth.refresh(user['refreshToken'])
    
    # Now user['idToken'] is fresh
  9. Run the Pyrebase4 test suite

    master

    Execute the test suite using pytest.

    MacOS Note: If you encounter issues on macOS, you may need to manually fix the shebang in the pytest executable to ensure it points to the correct Python binary in your virtual environment.

    pytest -s tests
  10. Initialize Pyrebase4 with a Service Account (Admin Mode)

    master

    By adding a serviceAccount key pointing to your service account JSON file in the configuration, the application will authenticate as an admin. This allows the server to disregard security rules for all database queries.

    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)
  11. Troubleshoot 'Index not defined' error

    master
    If you encounter an error indicating that an index is not defined, it means indexing has not been enabled for that specific database reference in the Firebase Console. You must enable indexing in your Firebase database rules to allow queries using order_by_child or similar methods.