Firebase database CRUD sample with Python Flask web application

  • The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client across different platforms. Firebase is a NoSQL database and persists data on the local storage, which enables Firebase based applications to work even when offline. The Firebase local database that persists in devices can be accessed directly from a mobile device or web browser. That means, using Firebase database we can develop web applications or mobile apps that will work on offline mode as well.

    In this tutorial we will create a python based web application using Flask framework. This is a simple application that lists a set of cars available in a showroom for sale. Users can add, edit or delete from this list. We will learn how to set up a Firebase database, connect to Firebase from a python web application, perform basic Read, Create, Update and Delete (CRUD) operations on a Firebase DB. firebase_admin library is used as the adapter to interact to Firebase DB from python.

  • Install Python and setup Virtual Environment

    Download and install the latest version of python from Python Website.

    Setting up virtual environment is not a must, but its is good to keep all your projects within a virtual environment. Here, we will proceed with a virtual environment.

    For that, go to the command prompt and cd to the folder where you are going to keep your project.
    Run command python -m venv CarSales to create a project folder CarSales and a virtual environment for it.
    Activate the VE using command:

    For Windows:
    CarSales\Scripts\activate.bat
    For Linux, macOS:
    source CarSales /bin/activate

    After VE activation, from cmd type cd CarSales to navigate to the project folder.

  • Install Flask and firebase-admin

    To install flask, run command pip install flask or pip3.9 install flask
    If not working use commands:

    For Windows:
    py -3.9 -m pip install flask
    For Linux, macOS:
    python3.9 -m pip install flask

    Similarly install firebase-admin using command pip install firebase-admin or pip3.9 install firebase-admin

    Run pip freeze or pip3.9 freeze to check if flask and firebase-admin installed successfully.

  • Initial steps for Flask Web Apps

    Follow these basic steps to set up your first Flask web application.
    Create a file named carsales.py (you can provide any name), inside CarSales folder and copy below code to it. carsales.py is going to contain your start-up code which is required to run your webapp. From command prompt navigate to CarSales folder and execute command py carsales.py or python carsales.py or py -3.9 -m carsales or python3.9 -m carsales depending on OS and Python version.

    from flask import Flask
    
    carsales = Flask(__name__)
    
    if(__name__ == "__main__"):
        carsales.run()
    

    This code imports Flask module and creates an object carsales of Flask class. Last 2 lines serves as the entry point of the app and starts the server. In cmd, we will see the below message.

        * Serving Flask app 'carsales' (lazy loading)
        * Environment: production
        Use a production WSGI server instead.
        * Debug mode: off
        * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    

    Copy the url http://127.0.0.1:5000/ to your browser and run. We will get the Not Found message as below.

    Flask and SQL Server - Not found

    This means that the Flask has handled the server set up and our application is ready. We will now have to set up our html pages and routing to handle page navigations.

  • Setting up First page

    We are going to keep a list page as the first page of the application.
    In Flask, all our HTML should be placed inside a folder named templates and static files like javascript or stylesheet should be placed inside static folder.So, create a folder structure as below within your application folder and add html file carslist.html inside templates folder.

    Flask and Firebase DB - First Page

    Add below code to carslist.html. To handle routing for this page, modify carsales.py as below. This code imports render_template module and sets up the default route.

    In command prompt. click Ctrl + C to stop the application and run command py -3.9 -m carsales or python3.9 -m carsales or py carsales or python carsales (Varies depending on OS and the python version used). This process is to be done each time we make any changes and want to reload the page. Some times, after stopping flask application from command prompt, just reloading the html will not give you the desired output. If any such issues are faced, close the web page and reopen.

  • Firebase Database Initial Setup

    To connect to a Firebase database, we have to configure Firebase project and database from the Firebase console and generate a private key configuration file.
    If you are not familiar with the process, refer page Setting up Firebase database for the first time.

  • Inserting initial set of data

    Add a new file initialdata.py within the same virtual environment and paste the below code.
    Copy the configuration file that we downloaded from the previous step to the virtual environment folder and rename it to carsales-admin-key.json. Also copy your database URL from Firebase console and paste it in the code.

    In the code, we are importing firebase_admin library and then connecting to the Firebase database using the private key configuration file. Then, we are declaring a new collection CarsList (this is similar to a table in SQL based databases) and inserting 5 records to this.

    Execute the code using the command py initialdata.py

    Copied
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import db
    
    cred = credentials.Certificate("carsales-admin-key.json")
    firebase_admin.initialize_app(cred, {
        "databaseURL": "https://projectname-xxxxxxxxxxx-rtdb.firebaseio.com/" #Your database URL
    })
    
    dbref = db.reference("CarsList")
    dbref.push( { "ID": 1, "Name": "Toyota Camry", "Year": 2018, "Price": 2000 } )
    dbref.push( { "ID": 2, "Name": "Honda Civic", "Year": 2019, "Price": 2200 } )
    dbref.push( { "ID": 3, "Name": "Chevrolet Silverado", "Year": 2017, "Price": 1800 } )
    dbref.push( { "ID": 4, "Name": "Ford F-150", "Year": 2020, "Price": 2500 } )
    dbref.push( { "ID": 5, "Name": "Nissan Altima", "Year": 2021, "Price": 3000 } )
    
    print(dbref.get())
    

    dbref.get() fetches the inserted records from the collection. You can see that a unique key also got generated automatically for each inserted record. This key is required to identify records while update, delete, etc.

    Copied
    {
    	'-N3w9V6DgdBXn3eYV4S2': {'ID': 1, 'Name': 'Toyota Camry', 'Price': 2000, 'Year': 2018},
    	'-N3w9VBcxfkrsSHZyLVZ': {'ID': 2, 'Name': 'Honda Civic', 'Price': 2200, 'Year': 2019},
    	'-N3w9VGh6kLhAkhO-mA9': {'ID': 3, 'Name': 'Chevrolet Silverado', 'Price': 1800, 'Year': 2017},
    	'-N3w9VLhw_EZmUJiwXTe': {'ID': 4, 'Name': 'Ford F-150', 'Price': 2500, 'Year': 2020},
    	'-N3w9VQw0aZtLbq-vFEC': {'ID': 5, 'Name': 'Nissan Altima', 'Price': 3000, 'Year': 2021}
    }
    
  • Fetch data from Firebase DB and list

    carslist.html is going to hold the list of cars available for sale. To list the items, add below code in body of html and modify carsales.py main method as below.
    In python file, we are imorting firebase-admin library and using its different methods establishing a connection to the Firebase DB. Note that the connection should be established only once. So we are calling the connectDB() only once at the time of initializing from __main__ method.
    In html, we are looping through the items and list it as table rows. Copy the below HTML and paste it to the body of carslist.html.

    For styling we will use Bootstrap 5. Add below 2 lines inside head of html.

    
        <link rel="stylesheet" crossorigin="anonymous"
    	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" >
        
    	<script crossorigin="anonymous"
    	src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" >
    	</script>
    
    

    On rerun, we will get below output window.

    Flask and SQL Server - List Items
  • Insert new item to Firebase DB

    Add a new button in the carslist.html above the table.

        <a class="btn btn-primary" href="addcar">Add New Car</a>
    

    Add new html file, addcar.html and place below code. Add below code in caresales.py as the second route below main method.

    Now we have to import request and redirect. For that, change first line of caresales.py as below.

    from flask import Flask, render_template, request, redirect
    

    In the python code, we are defining a new route for addcar. We are using the same method for GET and POST. GET is just rendering addcar.html. In POST, we are reading data from form controls and save data to table using push() method and then redirect to list page.

    In HTML page, we are defining a form with 4 text boxes. Each has a name provided. This name is used in the python file while reading data from controls.
    On rerun, we can navigate to Create page as below and add new Car.

    Flask and SQL Server - Add an Item
  • Update items - Firebase DB

    For update and delete add 2 links in the carslist.html page as below.

    Copied
    <table class="table">
        <thead>
            <tr>
            <th scope="col">Id</th>
            <th scope="col">Name</th>
            <th scope="col">Year</th>
            <th scope="col">Price</th>
            <th scope="col">Edit</th>
            <th scope="col">Delete</th>
            </tr>
        </thead>
        <tbody>
            {% for car in cars %}
                <tr>
                    <td>{{ car.id }}</th>
                    <td>{{ car.name }}</td>
                    <td>{{ car.year }}</td>
                    <td>{{ car.price }}</td>
                    <td><a href='updatecar/{{ car.id }}'>Edit</a></td>
                    <td><a href='deletecar/{{ car.id }}'>Delete</a></td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    

    First, in addcar.html, in order to populate the values, use the value attribute and bind the car object values as in html provided below.

    Then, in carsales.py, add new updatecar route.
    To update a record, we need the unique key value that was automatically generated at the time of insert. To get this, we are looping through the records and using the selected ID, we are retrieving and storing the key at the time of page load (GET). Then in POST, call the update() method to modify the selected item.

    Note: Disable the ID textbox to not make changes to ID. Here we are not doing it and if ID is changed no update will happen.

    After the above changes, update will work, but create will throw an error. To fix this, change the render_template line of addcar as below.

    return render_template("addcar.html", car = {})
    

    We are binding an empty car object to make it working.

  • Delete an Item from Firebase DB

    For delete, add a new route deletecar, get the unique key and call delete() method as below.

    Copied
    @carsales.route('/deletecar/<int:id>')
    def deletecar(id):
        tblCars = dbconn.get()
        for key, value in tblCars.items():
            if(value["ID"] == id):
                deletekey = key
                break
        delitem = dbconn.child(deletekey)
        delitem.delete()
        return redirect('/')
    
  • Flask CRUD with Firebase DB - Complete code

    Complete code is placed below.

Absolute Code Works - Python Topics