Integrate MongoDB with Flask
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 cataloguing and editing suites, CAD packages, record keeping programs, and so forth
What is MongoDB?
MongoDB is a document-oriented database that stores data in JSON-like documents with dynamic schema. It means you can store your records without worrying about the data structure such as the number of fields or types of fields to store values. MongoDB documents are similar to a JSON object.
Difference between MongoDB and SQLite
The difference between MongoDB and SQLite is that MongoDB is a document-oriented database management system and it is schema-less while SQLite is a Relational database management system and it needs a schema. the field names and their information is to be supplied prior to storing data but in MongoDB, the field name is to be given with the data itself.
Overview of the forthcoming
In this article, I will demonstrate how to build two simple web pages to take input from users and then store the data in respective databases using the Flask framework.
This is the code of “form_sqlite.html”. The webpage created by this code will be used to fetch data from users and data will be stored in SQLite database.
########## form_sqlite.html #############<form method="GET" action="/add_data_sqlite">
</br>
<b>Enter the data to SQLite database</b>
<br>
Name: <input name="name" /> <br>
Age: <input name="age" /> <br>
city: <input name="city" /> <br>
<input type="submit" value="Add to databse" /></form>
This one is “mdbform.html”. Webpages created with this code will be used to get data from users to be stored in the MongoDB database.
############# mdbform.html ############<form method="GET" action="/add_data_mdb" method="GET" >
<br>
<b><c> Enter Data to Mongodb Database </c> </b> ,<br>
Enter the name of the Database <input type="text" name="db_name" /> <br>
Enter the name of collection in that database <input name="coll_name" /> <br>
Enter the data in json format <input type="text" name="data" />
<input type="submit" value="submit" /></form>
Python file “app.py”. This is the base code that we will run using the Flask framework.
from flask import Flask , request , render_template
from flask_sqlalchemy import SQLAlchemyapp = Flask("db-app")##### Connecting with SQLite ##########app.config['SQLALCHEMY_DATABASE_URI'] = r'sqlite:///C:\Users\Dell\Desktop\python\mydb\data.sqlite'
db = SQLAlchemy(app)class record(db.Model):
name = db.Column(db.Text)
age = db.Column(db.Integer)
city = db.Column(db.Text)
id = db.Column(db.Integer , primary_key=True)
def __init__(self,n,a,c):
self.name = n
self.age = a
self.city = c@app.route("/form_sqlite")
def myform():
data = render_template("form_sqlite.html")
return data
@app.route("/add_data_sqlite" )
def add_data_sqlite():
n = request.args.get("name")
a = request.args.get("age")
c = request.args.get("city")
db.create_all()
obj = record(n ,a ,c)
db.session.add(obj)
db.session.commit()
return "successfull"
####### Connect with MongoDB #########
from pymongo import MongoClient
from ast import literal_evalclient = MongoClient('mongodb://127.0.0.1:27017')
@app.route('/mdbform')
def mdbform():
data = render_template('mdbform.html')
return data
@app.route('/add_data_mdb' , methods=['GET'])
def add_data_mdb():
db_name = request.args.get('db_name')
coll_name = request.args.get('coll_name')
datadict = request.args.get('data')
mydb = client[db_name]
mycoll = mydb[coll_name]
mycoll.insert(eval(datadict))return "success"
This file is named “app.py” so it can run using the “# flask run” command. We can also run this file using the python command “# python app.py” but the former is a recommended practice while using Flask.
Further, we have to make a folder “templates” to keep the template files so that Flask can easily find them. eg “mdbform.html” and “form_sqlite.html” in our case.
Explanation of code
from flask import Flask , request , render_template
from flask_sqlalchemy import SQLAlchemyapp = Flask("db-app")##### Connecting with SQLite ##########app.config['SQLALCHEMY_DATABASE_URI'] = r'sqlite:///C:\Users\Dell\Desktop\python\mydb\data.sqlite'db = SQLAlchemy(app)
In the above snippet first, we have imported some modules like
- ‘Flask’ for flask framework,
- ‘request’ for getting data from the webpages
- ‘render_template’ for putting the template webpages on flask app
- ‘SQLALchemy’ to interact with the SQLite database
Then we have created an instance (app) of the Flask class whose name is ‘DB-app’. In the next line, we have given the URL SQLite database running in the backend. At last, we have created an instance (dB) of SQLALchemy class which is connected with the flask instance ‘app’.
class record(db.Model):
name = db.Column(db.Text)
age = db.Column(db.Integer)
city = db.Column(db.Text)
id = db.Column(db.Integer , primary_key=True)
def __init__(self,n,a,c):
self.name = n
self.age = a
self.city = c
@app.route("/form_sqlite")
def myform():
data = render_template("form_sqlite.html")
return data
@app.route("/add_data_sqlite" )
def add_data_sqlite():
n = request.args.get("name")
a = request.args.get("age")
c = request.args.get("city")
db.create_all()
obj = record(n ,a ,c)
db.session.add(obj)
db.session.commit()
return "successful"
In the above code, I have defined a class (record) inherited form class ‘db.Model’. In this class, a schema is created for the incoming data by specifying the field name and their data types.
Then I am routing the app to the URLs. Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. Using the route() decorator to bind a function to a URL.
The first route ‘/form_sqlite’ will display the HTML page “form_sqlite.html”
The second route will get the data from the webpage and upload data to the SQLite database. Here we have used session.add() to add data to db instance then session.commit() to permanently write data to system storage from RAM.
####### Connect with MongoDB #########
from pymongo import MongoClient
from ast import literal_evalclient = MongoClient('mongodb://127.0.0.1:27017')
@app.route('/mdbform')
def mdbform():
data = render_template('mdbform.html')
return data
@app.route('/add_data_mdb' , methods=['GET'])
def add_data_mdb():
db_name = request.args.get('db_name')
coll_name = request.args.get('coll_name')
datadict = request.args.get('data')
mydb = client[db_name]
mycoll = mydb[coll_name]
mycoll.insert(eval(datadict))
return "success "
Here we imported ‘MongoClient’ from pymongo library which provides API for MongoDB and ‘literal_eval’ from the asr library to convert the string to dictionary datatype.
First route ‘/mdbform’ provides the ‘mdbform.html’ template file to flask and return its data to the second route ‘/add_data_mdb’ which insert the data in MongoDB.
Running the Flask App
To run the Flask app we have to to the directory in which we have kept app.py and enter the command ‘ flask run ‘. It will automatically detect app.py in that folder and run for you. This will keep on running until you manually close it. The requests to this will be displayed in the command prompt.
After this ensure that SQLite and MongoDB servers are running in the background. Then use the URL visible on the command prompt — http://localhost:5000/ and add the route name which you would like to visit.
Use — http://localhost:5000/form_sqlite to add data to SQLite database.
After adding data click on “Add to database”. The browser will take you to the “/add_data_squlite” route where data will add to the database and you will see a success message.
To add data to MongoDB we have added “/mdbform” at the end of the URL — http://localhost:5000/mdbform.
Here if the name of the database and collection is known then it will use them but if they don’t exist it will create new ones. the data should be entered in proper JSON format. eg. {‘name’ : ‘jack’ , ‘class’ : 4 , ‘city’ : ‘Jaipur }
After you click the submit button, you will land to route “/add_data_mdb” and data will be inserted into the database.
To view the uploaded data in the SQLite database, here I am using the “DB Browser for SQLite” app. It is a lightweight app to provide a GUI interface and to query data stored in an SQLite database.
To see the data inserted in the MongoDB database. Here I am using “MongoDB Compass” app. It is an app to provide a GUI interface to process data in the MongoDB database.
Get the code: https://github.com/srasthychaudhary/MongoDB-Flask
THANK YOU