Integrate MongoDB with Flask. Creating Simple Student Data Form

Rajdeep Singh
7 min readSep 28, 2021

Task 33: Integrate MongoDB with flask. Replace the SQlite Database which was explained by sir in demonstration in Flask Session with MongoDB

What is a flask?

Flask is a web framework. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial website.

Flask is part of the categories of the micro-framework. Micro-framework is normally a framework with little to no dependencies to external libraries. This has pros and cons. Pros would be that the framework is light, there is little dependency to update and watch for security bugs, cons is that sometimes you will have to do more work by yourself or increase yourself the list of dependencies by adding plugins. In the case of Flask, its dependencies are:

What is MongoDB?

MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).

A simple MongoDB document Structure:

The advantages of using documents are:

  • Documents (i.e. objects) correspond to native data types in many programming languages.
  • Embedded documents and arrays reduce the need for expensive joins.
  • The dynamic schema supports fluent polymorphism.

SQL databases store data in tabular format. This data is stored in a predefined data model which is not very much flexible for today’s real-world highly growing applications. Modern applications are more networked, social and interactive than ever. Applications are storing more and more data and are accessing it at higher rates.

Relational Database Management System(RDBMS) is not the correct choice when it comes to handling big data by the virtue of their design since they are not horizontally scalable. If the database runs on a single server, then it will reach a scaling limit. NoSQL databases are more scalable and provide superior performance. MongoDB is such a NoSQL database that scales by adding more and more servers and increases productivity with its flexible document model.

Today we will be building a Simple Student data gathering form using flask and storing the data in MongoDB

Prerequisites

  1. Python (3.x.x)
  2. Flask framework
$ pip install flask

3. PyMongo

$ pip install pymongo

4. MongoDB Software

Next, we will be creating our project “flask-mongodb” directory as shown below

The index.html file contains the frontend part. The content are as below, copy it and save it in the same way as shown above

<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<style>
@import url(https://fonts.googleapis.com/css?family=Raleway:400,500);
html,
body {
background-color: #00bfff;
text-align: center;
font-family: 'Raleway', Helvetica, sans-serif;
min-width: 320px;
}
header {
font-size: 2em;
font-weight: bold;
margin: 20px;
}
#form-outer {
background-color: rgb(250, 250, 250);
margin: 0 auto;
border-radius: 4px;
width: 75%;
max-width: 900px;
padding: 10px;
padding-top: 20px;
}
.labels {
display: inline-block;
text-align: right;
width: 40%;
padding: 5px;
vertical-align: top;
margin-top: 10px;
}
.rightTab {
display: inline-block;
text-align: left;
width: 48%;
vertical-align: middle;
}
.input-field {
height: 20px;
width: 280px;
padding: 5px;
margin: 10px;
border: 1px solid #c0c0c0;
border-radius: 2px;
}
#userAge {
width: 40px;
}
.userRatings,
input[type="checkbox"] {
float: left;
margin-right: 5px;
}
#submit {
background-color: #1a8cff;
border-radius: 4px;
color: white;
font-size: 1em;
height: 40px;
width: 96px;
margin: 10px;
border: 0px solid;
}
#reset {
background-color: #1a8cff;
border-radius: 4px;
color: white;
font-size: 1em;
height: 40px;
width: 96px;
margin: 10px;
border: 0px solid;
}
.dropdown {
height: 35px;
width: 140px;
padding: 5px;
margin: 10px;
margin-top: 15px;
border: 1px solid #c0c0c0;
border-radius: 2px;
}
.radio, .checkbox {
position: relative;
left: -43px;
margin-left: 10px;
display: block;
padding-bottom: 10px;
}
@media screen and (max-width: 833px) {
.input-field {
width: 80%;
}
select {
width: 90%;
}
}
@media screen and (max-width: 520px) {
.labels {
width: 100%;
text-align: left;
}
.rightTab {
width: 80%;
float: left;
}
.input-field {
width: 100%;
}
select {
width: 100%;
}
}
</style>
<h1 id="title">Student Data Form</h1>
<div id="form-outer">
<p id="description">
To know the details of students
</p>
<form id="survey-form" method="POST" action="/data">
<div class="rowTab">
<div class="labels">
<label id="name-label" for="name">Full Name: </label>
</div>
<div class="rightTab">
<input autofocus type="text" name="name" id="name" class="input-field" placeholder="Enter your name" required>
</div>
</div>

<div class="rowTab">
<div class="labels">
<label id="email-label" for="email">Email: </label>
</div>
<div class="rightTab">
<input type="email" name="email" id="email" class="input-field" required placeholder="Enter your Email">
</div>
</div>
<div class="rowTab">
<div class="labels">
<label id="number-label" for="age">Age: </label>
</div>
<div class="rightTab">
<input type="number" name="age" id="number" min="1" max="125" class="input-field" placeholder="Age" required>
</div>
</div>

<div class="rowTab">
<div class="labels">
<label id="dob-label" for="dob">D.O.B: </label>
</div>
<div class="rightTab">
<input type="date" name="dob" id="iddob" class="input-field" required>
</div>
</div>

<div class="rowTab">
<div class="labels">
<label for="department">Department: </label>
</div>
<div class="rightTab">
<select id="dropdown" name="department" class="dropdown">
<option disabled value>Select an option</option>
<option value="Information Technology">IT</option>
<option value="Computer Science Engineering">CSE</option>
<option value="Electronics and Communication Engineering">ECE</option>
<option value="Mechanical Engineering">MECH</option>
<option value="Civil Engineering">CIVIL</option>
<option value="other">Other</option>
</select>
</div>
</div>

<div class="rowTab">
<div class="labels">
<label for="gender">Gender: </label>
</div>
<div class="rightTab">
<ul style="list-style: none;">
<label class="radio-inline"><input name="gender" value="Male" type="radio">Male</label>
<label class="radio-inline"><input name="gender" value="Female" type="radio">Female</label>
<label class="radio-inline"><input name="gender" value="others" type="radio">Others</label>
</ul>
</div>
</div>
<div class="rowTab">
<div class="labels">
<label for="address">Address: </label>
</div>
<div class="rightTab">
<textarea id="comments" class="input-field" style="height:50px;resize:vertical;" name="address" placeholder="Enter your address here..."></textarea>
</div>
</div>
<div class="rowTab">
<div class="labels">
<label for="pincode">Pincode: </label>
</div>
<div class="rightTab">
<input type="number" name="pincode" id="idpincode" class="input-field" style="height:20px;resize:vertical;" placeholder="6 - - - - -"></div>
</div>

<div class="rowTab">
<div class="labels">
<label for="language">Language Known: </label>
</div>
<div class="rightTab">
<ul id="language" style="list-style: none;">
<li class="checkbox"><label><input name="language1" value="English" type="checkbox" class="userRatings">English</label></li>
<li class="checkbox"><label><input name="language2" value="Marathi" type="checkbox" class="userRatings">Tamil</label></li>
<li class="checkbox"><label><input name="language3" value="Hindi" type="checkbox" class="userRatings">Hindi</label></li>
<li class="checkbox"><label><input name="language5" value="Kannada" type="checkbox" class="userRatings">Kannada</label></li>
<li class="checkbox"><label><input name="language7" value="others" type="checkbox" class="userRatings">Others</label></li>
</ul>
</div>
</div>

<button id="submit" type="submit">Submit</button>
<button id="reset" type="reset">Reset</button>
</form>
</div>

Then comes the main flask application I have created “app.py” which contains all the required code. Let’s understand it bit by bit

# import necessary modulesfrom flask import Flask, request, render_template
from pymongo import MongoClient

The above packages are required, hope you have installed them from the above source

# define the mongodb client
client = MongoClient(port=27017)
# define the database to use
db = client.student_data

Next, we have defined the MongoDB client and the port on which it is working. In my case, I am using the local MongoDB software installed on my machine. cloud-based can also be implemented.

Then we define the database we will be using, we don’t require to implicitly create the database because if the given database is not present the MongoDB will create one for us.

The above image is from MongoDBCompass a GUI interface from MongoDB. As we can see there is no database named “student_data”. When we run the program we can see that the database gets automatically created for us

# define the flask app
app = Flask(__name__)
# define the home page route
@app.route('/')
def hello_world():

return render_template("index.html")

Next, we define and initialize the flask app. Then create a simple route i.e home page of our application

# route to get data from html form and insert data into database
@app.route('/data', methods=["GET", "POST"])
def data():
data = {}
if request.method == "POST":
data['Name'] = request.form['name']
data['Email'] = request.form['email']
data['Age'] = request.form['age']
data['DOB'] = request.form['dob']
data['Department'] = request.form['department']
data['Gender'] = request.form['gender']
data['Address'] = request.form['address']
data['Pincode'] = request.form['pincode']
lang = []
for i in "1234567":
try:
if request.form['language' + i] != "":
lang.append(request.form['language' + i])
except Exception as e:
pass
data['Language'] = lang
db.studentData.insert_one(data)
return render_template("index.html")

Next, we define a ‘/data’ route which works as a Post method and gets the data from the HTML form when submitted and stores it into the MongoDB database

# start the flask server
if __name__ == '__main__':
app.run(debug=False)

Finally, we will start the flask server, by default flask server runs on port 5000 so we can access the application by going to “localhost:5000” on our system. We will see as shown below

As we have seen before that there is no database, it will be created on the fly. Now fill in the information and submit it after that we can see that the data is stored in the database.

After, we submit the data will get stored in the database as shown below

--

--