Integrating MongoDB with Flask

Sainadh
4 min readJul 10, 2021
Photo by Alex Kondratiev on Unsplash

In this blog, you will learn about flask, how to use a database with flask, connecting to mongodb, atlas and building a small app.

This is my second blog in the series of Getting Started with MongoDB, check out my previous blog click here.

Flask

Flask is one of the python libraries to build web applications and API (Application Programming Interface). It is light weight, easy to learn and implement. Acts has a backend.

To go deeper into the implementation part, you should have some basic knowledge on python and how decorators work in python.

# To load any library or package basic implementation
import flask # loading the entire library
from flask import Flask # loading only the functions from library
from flask import * # load all the functions from the library

For implementing a web application, we require HTML, CSS, and JavaScript.

For rendering a html file and a basic implementation.

from flask import Flask, render_templateapp = Flask('__main__')@app.route('/') # here we define the context for the url
def index():
#Store the html and css files in templates folder
return render_template('index.html')
if __name__ == '__main__':
app.run(host = '0.0.0.0', port=8080) # starting the web app in your public ip at port 8080.

Connecting to MongoDB

We connect MongoDB to our flask in 2 different ways.

One way is using the flask_sqlalchemy library which is built for flask to operate the database for building models, creating sessions for a user, useful when building big websites.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask("Myapp")
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb/db.sqlite'

Second way is to use pymongo library for directly interacting with the application. Here we use pymongo as our focus is to use MongoDB as a Database of our choice.

from pymongo import MongoClient
#connecting a mongodb
db = MongoClient("mongodb://127.0.0.1:27017")
notes = db['app']['notes'] # getting our collection

Implementing MongoDB with Python

We are going to implement a Notes taking Web Application, the usual operations we perform on any note taking app is to create, update and delete.

Create

We first see how to do above operations with mongo and then implement with python.

# Creating a note is like inserting data to DB
> db.notes.insert({'title': 'Morning Notes', 'description': 'Wake up early and do excercise', 'status': 'doing'})

Python

notes.insert({'title':'Write a Blog', 'description':'Blog on MongoDb to integrate flask app', 'status':'working on it'})

Update

To update any information, we require a primary key, by default MongoDB provides a primary key in the form of ID. We use the ObjectID to update the information.

We can simultaneously update many objects or a single object

> db.notes.update_one({'_id':ObjectId('60bce339228181eb01f3523a')}, {$set : {'status': 'done'}})

In python we can do similarly as above but we require the ObjectID to identify the primrary key. We can load this function from bson library which helps us to encode and decode.

from bson.objectid import ObjectId
notes.update_one({'_id': ObjectId('60bce339228181eb01f3523a')}, {'$set': {'status': 'done'}})

Delete

Deletion of an object also requires the primary key.

mongo: -

> db.notes.delete_one({'_id':ObjectId("60e7edfd29ae1794a7a7f3e9")})

Python: -

notes.delete_one({'_id':ObjectId('60bce339228181eb01f3523a')})

Python APP

We can implement it in different ways. One way is to implement frontend completely using html, css, javascript, flask for building API’s and use javascript to call the data from flask api.

Another way is to retrieve the data from database in the flask app and send it to the frontend. Here we no need to implement any API’s.

Terminology

Some basic terms we regularly use when building any webapplication.

Get :- It is one of the HTTP (Hyper Text Transfer Protocol) methods, where we can retrieve the information from the URL. Generally used to retrieve the data , do query and display the data.

Post :- It is also one of the HTTP methods, where it can send loads of data from the source to the server.

Request :- Request method identifies the required action to be performed like post.

Here I am not goanna discuss about the HTML, CSS and JavaScript code.

There are multiple ways to build a single app, here I taken simple approach which is to understand.

To retrieve the information from the frontend app.

# To retrieve the data
title = request.form.get('title')
# As we must use the same code multiple times
p_data = lambda x: request.form.get(x) # simple lambda function

We put all the operations together.

@app.route("/", methods= ['GET', 'POST'])def index():  if request.method == "POST":     title = p_data('title')     desc = p_data('description')     status = p_data('status')     operation = p_data('operation')     id = p_data('id')         if operation == 'create':             notes.insert({'title':title, 'description':desc, 'status':status})         elif operation == 'update':             notes.update_one({'_id':ObjectId(id)},{'$set' :{'title':title,'description':desc,'status':status}})         elif operation == 'remove':             notes.delete_one({'_id':ObjectId(id)})         elif operation == 'edit':             data = notes.find({"_id": ObjectId(id) })             return render_template('edit.html', note = data[0])         else:             pass     data = notes.find()     return render_template("index.html",notes=data)

I created a separate page for writing the note.

@app.route("/create")def create():   return render_template("create.html")

MongoDB Atlas

MongoDB provides a service known as Atlas.

With the help of Atlas, you can create a database cluster with Master or Parent node and Worker or Child nodes on the cloud platform of your choice.

As data is growing at faster rate and most of the operations are performed on the database, if a database crashes, entire website goes down and results in Single Point of Failure (SPOF).

To avoid SPOF, provide reliable and durable database services we must use a cluster.

In the cluster master nodes take care of the cluster and looks after the worker nodes, if anything goes down master node takes care of it and avoids lots of failures.

Worker nodes only store the information and do the basic work.

Conclusion

We have done basic operations on monogdb, connected it to a Web Application, discussed about Atlas and python code for building the web app.

In the next blog, you will be reading about Data Analysis with MongoDB.

Thank you for reading the blog and if you have any issues please comment below.

--

--

Sainadh

Devops and automation export, explorer, opensource enthusiast, follow for more content related to devops and easy way to do the things.