Using Flask with MongoDB and SQLite database
Vivek Sharma
RedHat Certified in Containers and Kubernetes(EX180) ||Arth || Aspiring DevOps Engineer || Python || Docker || Ansible || Jenkins || Kubernetes || OpenShift || Terraform || GitHub || AWS || AZURE
Task Description??
?? Integrate MongoDB with flask. Replace the SQlite Database which was explained by sir in demonstration in Flask Session with MongoDB.
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 cataloging and editing suites, CAD packages, record keeping programs, and so forth
What is MongoDB ?
MongoDB is a document-oriented database which 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 JSON object.
The major 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 need a schema. the field names and their information is to be supplied prior storing data but in MongoDB the field name are to be given with the data itself .
Overview of the forthcoming
In this Article I will demonstrate the How to build two simple webpages to take input form user and then store the data in store the data in respective databases using the Flask framework.
This is code of "form_sqlite.html" . The webpage created by this webpage will be used to fetch data form user 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 user to be stored in 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 which we will run using Flask framework.
from?flask?import?Flask?,?request?,?render_template
from?flask_sqlalchemy?import?SQLAlchemy
app?=?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_eval
client?=?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 name as "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 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?SQLAlchemy
app?=?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
领英推荐
Then we have created 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?"successfull"
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 webpage and upload data to sqlite database. Here we have used session.add() to add data to db instance then session.commit() to pemanently write data to system storage from RAM.
#######?Connect?with?MongoDB #########
from?pymongo?import?MongoClient
from?ast?import?literal_eval
client?=?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 provide API for MongoDB and 'literal_eval' from 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 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 the directory in which we have kept app.py and enter 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 promp.
After this ensure that SQLite and MongoDB servers are running in background. Then use the URL visible on the command prompt - https://localhost:5000/ and add the route name which you would like to visit.
Use -- https://localhost:5000/form_sqlite to add data to SQLite database.
After adding data click on "Add to database" . Browser will take you to "/add_data_squlite" route where data will added to database and you will see a success message.
To add data to MongoDB we have add "/mdbform" at the end of the URL -- https://localhost:5000/mdbform .
Here if name of 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 to the database.
To view the uploaded data in SQLite database, here I am using "DB Browser for SQLite" app . It is a lightweight app to provide GUI interface and to query data stored in SQLite database.
To see the data inserted in MongoDB database. Here I am using "MongoDB Compass" app . It is app to provide GUI interface to process data in MongoDB database.
THANK YOU FOR READING.......