Using Flask with MongoDB and SQLite database(33)

Lakshmi Priya Patro
4 min readJan 24, 2022

What is MongoDB?

MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It is categorized under the NoSQL (Not only SQL) database because the storage and retrieval of data in MongoDB are not in the form of tables.

What is Flask?

Flask is a web framework, it is a Python module that lets you develop web applications easily. Flask gives the developer varieties of choice when developing web applications, it provides you with tools, libraries, and mechanics that allow you to build a web application.

What is SQLite?

SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. SQLite is the most used database engine in the world. SQLite is built into all mobile phones and most computers and comes bundled inside countless other applications that people use every day.

SQLite is often used as the on-disk file format for desktop applications such as version control systems, financial analysis tools, media cataloging, and editing suites, CAD packages, record keeping programs, and so forth.

In this Article, I will demonstrate how to build webpages to take input and then store the data database using the Flask framework.

There are several Flask extensions for integrating MongoDB, here we’ll be using the Flask-PyMongo extension.

We will also be working on a simple Todo-List API to explore the CRUD capabilities of MongoDB.

Let's start…

Step-1: Setup and Configuration

To follow, we will need to have access to a MongoDB instance. Here we can get one from MongoDB Atlas or we can also use a local instance. We will be using a local instance on our own personal machine.

To install a local instance of MongoDB, head over to their official documentation website for instructions on how to download and install it.

We will also need to have Flask installed, and if don’t, we can do so with the following command:

pip install flask

Next, we need to set up Flask-PyMongo, which is a wrapper around the PyMongo python package.

PyMongo is a low-level wrapper around MongoDB, it uses commands similar to MongoDB CLI commands for:

  1. Creating data
  2. Accessing data
  3. Modifying data

It doesn’t use any predefined schema so it can make full use of the schemaless nature of MongoDB.

To begin using Flask-PyMongo, we need to install it with the following command.

pip install Flask-PyMongo

Step-2: Connecting to a MongoDB Database Instance with Flask

Before we actually perform any work, we want to connect our MongoDB instance to the Flask application. We’ll start off by importing Flask and Flask-PyMongo into our app:

from flask_pymongo import PyMongo
import flask

Next, we’ll create a Flask app object:

app = flask.Flask(__name__)

Which we’ll then use to initialize our MongoDB client. The PyMongo Constructor (imported from flask_pymongo) accepts our Flask app object, and a database URI string.

This ties our application to the MongoDB Instance:

mongodb_client = PyMongo(app, uri="mongodb://localhost:27017/todo_db")
db = mongodb_client.db

The URI string could also be assigned to the key MONGO_URI in app.config

app.config["MONGO_URI"] = "mongodb://localhost:27017/todo_db"
mongodb_client = PyMongo(app)
db = mongodb_client.db

Once the application has a connection to the instance, we can start implementing the CRUD functionality of the application.

Step-3: Create Documents — Adding New Items to the Database

MongoDB works with collections, which are analogous to the regular SQL table. Since we’re making a TODO list app, we’ll have a todos collection. To reference it, we use the DB object. Each entity is a document, and a collection is really, a collection of documents.

To insert a new entry into our todos collection, we use the db.colection.insert_one() method. MongoDB works naturally with Python given its syntax for insertion, querying, and deletion.

When inserting a document into a MongoDB collection, you’d specify a dictionary with <field>s and <value>s. To insert a document into a MongoDB collection using Python as the middleman, you’ll pass in dictionaries that are built-in into Python.

Thus, to insert a new entity, we’ll do something along the lines of:

@app.route("/add_one")
def add_one():
db.todos.insert_one({'title': "todo title", 'body': "todo body"})
return flask.jsonify(message="success")

We could also add multiple entries at once using the db.colection.insert_many() method. The insert_many() method take a list of dictionaries and adds them to the collection:

@app.route("/add_many")
def add_many():
db.todos.insert_many([
{'_id': 1, 'title': "todo title one ", 'body': "todo body one "},
{'_id': 2, 'title': "todo title two", 'body': "todo body two"},
{'_id': 3, 'title': "todo title three", 'body': "todo body three"},
{'_id': 4, 'title': "todo title four", 'body': "todo body four"},
{'_id': 5, 'title': "todo title five", 'body': "todo body five"},
{'_id': 1, 'title': "todo title six", 'body': "todo body six"},
])
return flask.jsonify(message="success")

If we try and add a duplicate record, a BulkWriteError will be thrown, meaning that only records up to said duplicate will be inserted, and everything after the duplicate will be lost, so keep this in mind when trying to insert many documents.

If we want to insert only valid and unique records in our list, we will have to set the ordered parameter of the insert_many() method to false and then catch the BulkWriteError exception.

Thanks for Reading!!

--

--