Integrating MongoDB with Flask

suyog shinde
3 min readMay 31, 2021

What is Flask?

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions

What is MongoDB?

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need

Here, we have created a small and good-looking web app on the flask framework. Where a user can submit a form for his issue with health and the data which is provided in the form is stored in the MongoDB database.

Here my app name is “Flask+MongoDB” and created a directory structure as follows.

In the above directory structure:

The Flask-MongoDB is the main directory of our flask app

The static directory has three sub-directory css, js, and img where CSS files, javascript files, and images are stored accordingly.

The templates directory contains the HTML pages of our web app.

The app.py contains all the routes and the functions of the web app. Through this file, we are going to connect the MongoDB database to the web app.

Let me show you the app.py file.

First, we imported all the required packages

In the above file

app = Flask["MONGO_URI"] = YOUR_MONGODB_URL

This is used to specify the mongo database URL.

You first need to import MongoClient and create a connection:

from pymongo import MongoClient
client = MongoClient()

Then get your DB instance and collection (table):

db = client.my_database
collection = db.my_collection

Creating a function that takes data from the HTML page and forwards it to the Mongo database.

This function will take the data from the HTML page using the GET method and send the data to our collection.

The final look of the web app:

Keep Learning !! Keep Sharing !!

✔️If any quires you can reach out to me at LinkedIn: https://www.linkedin.com/in/suyogshinde/

--

--