Flask Integration

MDB backend integration with Flask for Standard

This article shows you how to integrate Flask backend application with MDB Standard UI Kit.


Prerequisites

Before starting the project make sure to install the following utilities:


Creating a new Flask application

Let's create a fresh Flask application so that we can go through all the steps together. For this tutorial we'll be using MySQL database.

Note: Depending on your OS you may need to use different commands. Copy the commands appropriate for your operating system.

Step 1

First, we need to create a project directory. We'll use a virtual environment to manage the dependencies for your project.

        
            
      mkdir myproject
      cd myproject
      python3 -m venv venv
    
        
    
        
            
      mkdir myproject
      cd myproject
      py -3 -m venv venv
    
        
    

Step 2

Before you work on your project, activate the corresponding environment. In case you are working on Windows and the command is not working, try this: source ./venv/Scripts/activate

        
            
      . venv/bin/activate
    
        
    
        
            
      venv\Scripts\activate
    
        
    

You should see venv folder added to your project directory, and in your terminal, the (venv) badge will be added before the path.

Step 3

Use the following command to install Flask.

        
            
    pip install Flask
    
        
    

Step 4

Open your project directory in the code editor. Create folder toDoApp, there create __init__.py file. Paste the content of the snippet below as its content.

        
            
    from flask import Flask, render_template

    app = Flask(__name__)
    
    def index():
        return render_template("index.html")
    
    if __name__ == "__main__":
        app.run()
    
        
    

Step 5

Install Flask SQLAlchemy library for handling MySQL database.

        
            
        pip install flask_sqlalchemy
      
        
    

Step 6

Creating a MySQL database.

In order to create a new database you need to run the following command.

Note: If you don't have MDB CLI installed yet, you can do it with NPM: npm install -g mdb-cli. Now log in with your MDB account, type: mdb login. If you don't have account yet you can create one using mdb register command.

        
            
          mdb database init -db mysql8
        
        
    
  • Create a new user
  • Provide username, password, database name and description.

CLI will display your username, password, database name and connections string. You will need this data in the next step. Now you can go to phpMyAdmin where you will be able to handle the administration of the MySQL database.

Note: the password must contain at least one uppercase letter, one lowercase letter, one number, one special symbol and have minimum length of 8.

Step 7

Edit __init__.py file by adding MySQL database configuration. Change the value between brackets for the database URL you got after creating a new MySQL Database from our starter.

        
            
      from flask_sqlalchemy import SQLAlchemy

      ...
      app.config['SQLALCHEMY_DATABASE_URI'] = '[Your database URL]'
      app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
      db = SQLAlchemy(app)
      
      class Todo(db.Model):
          id = db.Column(db.Integer, primary_key=True)
          name = db.Column(db.String(100))
          desc = db.Column(db.String(200))

      if __name__ == "__main__":
          db.create_all()
          app.run()

      
        
    

Step 8

Inside the toDoApp directory create folder templates, and there create an index.html file. There paste example content from the snippet below to see if the formatting is correct after you link CSS files.

        
            
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
      <title>Material Design for Bootstrap</title>
      <!-- Font Awesome -->
      <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
      <!-- Google Fonts -->
      <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
    </head>
    <body>
      <div class="container py-4 px-3 mx-auto">
        <h1>Hello, MDB and Flask!</h1>
        <button class="btn btn-primary">Primary button</button>
      </div>
    </body>
    </html>
    
        
    

Step 9

Run your app with a command from the snippet below. The first launch of the application will create tables associated with your model in your database.

        
            
      flask --app toDoApp --debug run
    
        
    

Now head over to http://127.0.0.1:5000/ and you should see your example page in the browser.


Install MDB

In this section, we will add MDB styles and JavaScript files to the example page.

Step 1

From base the project directory type the following command in the terminal. It will change the directory to toDoApp/static and initialize MDB CLI. From the list of starters select Standard.

Note: If you don't have MDB CLI installed yet, you can do it with NPM: npm install -g mdb-cli. Now log in with your MDB account, type: mdb login. If you don't have account yet you can create one using mdb register command.

        
            
        cd toDoApp
        mkdir static
        cd static
        mdb frontend init mdb5-free-standard
      
        
    

Step 2

In the head of the index.html file import static CSS files.

        
            
      <link rel="stylesheet" href="{{ url_for('static', filename='mdb5-free-standard/css/mdb.min.css' )}}">
      
        
    

Step 3

At the end of the body tag in the index.html file import static JS files.

        
            
        <script type="text/javascript" src="{{ url_for('static', filename='mdb5-free-standard/js/mdb.min.js' )}}"></script>
      
        
    
Now you're done

With MDB's CSS and JS fully loaded, after restarting the server your example page should work and you should see MDB styles applied to its content.


To Do App with MDB

In this section, we will present the capabilities of Ruby on Rails used with the MDB package by creating an example To Do App.

Step 1

Import request, redirect and url_for packages from Flask. Change a route assigned to the index and add routes to add, delete, and update.

        
            
        from flask import Flask, render_template, request, redirect, url_for

        ...
        @app.route("/")
        def index():
            todo_list = Todo.query.all()
            return render_template("index.html", tasks=todo_list)
        
        @app.route("/add", methods=["POST"])
        def add():
            name = request.form.get("name")
            desc = request.form.get("desc")
            new_todo = Todo(name=name, desc=desc)
            db.session.add(new_todo)
            db.session.commit()
            return redirect(url_for("index"))
        
        @app.route("/update/<int:todo_id>", methods=["POST"])
        def update(todo_id):
            todo = Todo.query.filter_by(id=todo_id).first()
            todo.name = request.form.get("name")
            todo.desc = request.form.get("desc")
            db.session.commit()
            return redirect(url_for("index"))
        
        @app.route("/delete/<int:todo_id>")
        def delete(todo_id):
            todo = Todo.query.filter_by(id=todo_id).first()
            db.session.delete(todo)
            db.session.commit()
            return redirect(url_for("index"))

        
        
    

Step 2

Change the content of the body tag in the index.html file to the content of the snippet below but don't remove the script tag that imports JavaScript files.

        
            
        <div class="container mt-5">
          <!-- Button trigger modal -->
          <div class="row pt-5">
              <div class="col text-center">
                  <button class="btn btn-primary" data-mdb-toggle="modal" data-mdb-target="#TaskModal" id="addTaskButton">Add task</button>
              </div>
          </div>
      
          <!-- Modal Add -->
          <div class="modal top fade" id="TaskModal" tabindex="-1" aria-labelledby="TaskModalLabel" aria-hidden="true">
              <div class="modal-dialog">
                  <div class="modal-content">
                      <div class="modal-header">
                          <h5 class="modal-title" id="taskModalLabel">Add task</h5>
                          <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <form action="/add" method="POST" id="taskForm">
                          <div class="modal-body">
                                  <div class="form-outline mb-4">
                                      <input name='name' type="text" id="editNameInput" class="form-control"/>
                                      <label class="form-label" for="editNameInput">Name</label>
                                  </div>
                                  <div class="form-outline mb-4">
                                      <input name="desc" type="text" id="editDescInput" class="form-control">
                                      <label class="form-label" for="editDescInput">Description</label>
                                  </div>
                                  <input name="id" type="hidden" id="taskId" >
                          </div>
                          <div class="modal-footer">
                              <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">
                                  Close
                              </button>
                              <button type="submit" class="btn btn-primary" id="confirmButton">Confirm</button>
                          </div>
                      </form>
                  </div>
              </div>
          </div>
      
          <!-- List of tasks -->
          <div class="row mt-3 p-5">
              <div class="col d-flex justify-content-center align-items-center">
                  <ul class="list-group list-group-light" style="min-width: 22rem;">
  
                      {% for task in tasks %}
                      <li class="list-group-item d-flex justify-content-between align-items-center gap-5" id="{{ task.id }}">
                          <div>
                              <div class="fw-bold name">{{ task.name }}</div>
                              <div class="fw-bold desc">{{ task.desc }}</div>
                          </div>
                          <div class="d-flex align-items-center">
                              <a class="btn btn-primary btn-floating me-2" data-mdb-toggle="modal" data-mdb-target="#TaskModal" onclick="setModalValues('{{ task.id }}')">
                                  <span class="fas fa-pen text-white"></span>
                              </a>
                              <form action='delete/{{ task.id }}' class="my-0">
                                  <button type="submit" class="btn btn-danger btn-floating">
                                      <span class="fas fa-trash text-white" title="delete"></span>
                                  </button>
                              </form>
                          </div>
                      </li>
                      {% endfor %}
                  </ul>
              </div>
          </div>
      </div>
        
        
    

Step 3

At the end of the body tag in the index.html add code from the snippet below.

        
            
          <script>
            const editNameInput = document.getElementById('editNameInput');
            const editDescInput = document.getElementById('editDescInput');
            const taskId = document.getElementById('taskId');
            const taskForm = document.getElementById('taskForm');
            const taskModalLabel = document.getElementById('taskModalLabel');
          
            function setModalValues(id) {
                const task = document.getElementById(id)
                editNameInput.value = task.querySelector('.name').innerText;
                editDescInput.value = task.querySelector('.desc').innerText;
                taskForm.action = `/update/${id}`;
                taskModalLabel.innerText = 'Edit task';
            }
          
            const addTaskButton = document.querySelector('#addTaskButton');
            addTaskButton.addEventListener('click', () => {
                taskForm.action = `/add`;
                taskModalLabel.innerText = 'Add task';
            })
          </script>
        
        
    

To access your application visit http://localhost:3000. There you should see a simple To Do app connected to MySQL database.


Optimization

If you want to further optimize your application please visit:


Backend features

Flask:

This example was created with the use of Flask. Our app is connected to MySQL database and is ready to receive get, post, put and delete requests.

MDB CLI:

The database in this example was created using MDB CLI with Graphical User Interface available under phpmyadmin.mdbgo.com


Frontend features

MDB UI KIT:

We have successfully added MDB UI Kit to the created app, with which we can build basic views very quickly.

Views and Layouts:

We have successfully integrated the backend with the MDB package and can send basic requests to the backend Flask application.