Integrating Flask With MongoDB
In this article, we will see how to integrate MongoDB with Flask.
Introduction
When we try to test our applications, first we set up a web server and configure it. Time consumes in this part of the setting environment. So, rather than focussing on the webserver, we can use some program that will handle it and we can focus on the application. Flask will fulfill this requirement.
Flask will do 2 things for us:
- Install webserver
- Runs the webserver
By default in the flask, app.py is the file that executes when we apply the flask run command. Below is the sample python code that utilizes the Flask program. Flask uses the route function to run the required web pages.
# importing Flask module form flask library from flask import Flask # creating the app app = Flask("myapp") # routing to search @app.route("/search") def search(): return ("search...") # routing to mail @app.route("/mail") def mail(): return("mail...")
Flask runs on 5000 port numbers with localhost loopback IP address.
If you want to connect to the mail app and search app.
#connecting to mail app http://127.0.0.1:5000/mail #connecting to search app http://127.0.0.1:5000/search
Now let's talk about MongoDB
In the SQL world schemas are fixed and work only on structured data. But in today's world sometimes we have to create schemas as and when required. We cannot afford to have a static schema most of the time we don't have all the attributes of the subject. So, MongoDB is one of the NoSQL databases that can handle unstructured data on the fly. Other NoSQL databases are Cassandra, Redis, and many more. These types of databases are known as a document-oriented database.
Vocabulary of MongoDB
- The record in MongoDB will be called Document.
- Creating a table(in SQL) for the data in MongoDB is known as Collection.
Let's integrate flask with MongoDB as now we are comfortable with the basics.
- There is no difference between creating a variable inside the class and creating schemas with different names.
- Classes we used for arranging the data and in the database world, we use the collection for arranging data.
Before starting we have to install libraries
- Install Flask Library
pip install Flask
2. Install mongoengine that will help us to integrate Flask and MongoDB.
pip install flask-mongoengine
Our Program
- The function config helps to connect to the local MongoDB server running on the 27017 port number.
#import module from flask import Flask from flask_mongoengine import MongoEngine import mongoengine as me #Creating app app = Flask("iiec") #Configuring the settings of MongoDB app.config['MONGODB_SETTINGS'] = { "db": "lw", } #Creating a MongoEngine Instance db = MongoEngine(app)
If you want to go into more depth and use some other features of the MongoEngine library you can check out the official documentation is given below 👇.
2. Below shown, class is the creation of the collection named as Student, we are declaring the fields.
class Student(me.Document): name = me.StringField(required=True) year = me.IntField() remarks = me.StringField()
3. In the below-shown code, we are instantiating the document, creating the Document for the collection Student. Inserted two documents in Student Collection. You can also try some other examples that will create schema on the fly. save() function helps us to store the document on the
#Instantiating the document # Creating Document student_1 = Student(name='Ayush',year=2021,remarks='OK') student_2 = Student(name='Aryan', year=2020,remarks='GOOD') student_1.save() student_2.save()
4. Now below is an example demonstrating how we can query on our collection.
#Querying about the data for student_name in Student.objects: if (student_name.remarks=='GOOD'): print (student_name.name)
5. Now let's check whether collection and documents are created in our database.
We can check that collection named student has been created and two documents have been inserted.
6. We can delete the documents in MongoDB by first finding their id and then passing the id in the delete() function.
Here is the GitHub link for the repository. You can check it out.
That's all. Thank you for reading.