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”.
PyMongo can be installed using pip:
pip install Flask
pip install PyMongo
pip install Flask-PyMongo
In Linux for python3
pip install Flask
pip3 install PyMongo
pip3 install Flask-PyMongo
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.
from flask_pymongo import PyMongo
from flask import Flask
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.
app = Flask(__name__)
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.
mongodb_client = PyMongo(app, uri="mongodb://localhost:27017/flask") db = mongodb_client.db
This ties our application to the MongoDB Instance.
Note: Make sure the MongoDB service is executing.
In windows to start MongoDB service
net start mongodb
- 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 email@example.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:
On submitting form
Now we have data in the MongoDB so our data will not vanish.