Integrate Flask with MongoDB

Let’s say we have created a sign up HTML form in Flask Application. We try to store the data related to sign up in the python dictionary. Now if our program terminates due to some reason then all the data store in the dictionary will vanish. To make our data persistent we need permanent storage. We can have permanent storage in two ways either through file handling or database storage.

Database are of two types relational and non-relational database. We are going to use the MongoDB non-relational database. No-relational database or No-SQL database are schema less which makes them flexible to have different number of fields, hierarchy of fields.

The PyMongo library allows interaction with the MongoDB database through Python; it is a native Python driver for MongoDB.

Flask-PyMongo bridges Flask and PyMongo and provides some convenience helpers.

Flask-PyMongo depends on recent versions of Flask and PyMongo, where “recent” is defined to mean “was released in the last 3 years”.

Installation

PyMongo can be installed using pip:

In Linux for python3

It is good to work in virtual environment if you are developing an application. For practice with just file you can do global install of libraries too.

Importing libraries:

An object of Flask class is our WSGI application. WSGI is web server gateway interface.

Flask constructor takes the name of current module (__name__) as argument.

Connecting to a MongoDB Database Instance with Flask

To connect to MongoDB instance PyMongo Constructor (imported from flask_pymongo) accepts our Flsk app object, and a database URI string.

URI Format: mongodb://localhost:27017/database_name

27017 is the default port for MongoDB instance.

This ties our application to the MongoDB Instance.

Note: Make sure the MongoDB service is executing.

In windows to start MongoDB service

CRUD operation

  • Creating flask collection in the flask database.
  • Updating a document in the flask collection with update_one function.

The above command will update the email to z@z.com for query fname: Shobhit. There are two records for fname: Shobhit but only one record will be updated.

To update multiple records use function update_many.

  • Deleting one of the document with delete_one function.
  • Deleting multiple document with delete_many function.

Above all two records for query fname: Shobhit deleted.

  • Reading multiple documents in database.

Output in terminal:

There is also find_one function to query a document in database.

Demonstration of Flask route:

Flask server

templates folder

  • index.html
  • signup.html
  • success.html

Running server.py

At http://localhost:5000/index.html

On submitting form

MongoDB

Now we have data in the MongoDB so our data will not vanish.

Learning Practicing Exploring