Flask and Sqlalchemy Tutorial for Database
Last Updated :
17 May, 2024
Flask is a micro web framework written in python. Micro-framework is normally a framework with little to no dependencies on external libraries. Though being a micro framework almost everything can be implemented using python libraries and other dependencies when and as required.
In this article, we will be building a Flask application that takes data in a form from the user and then displays it on another page on the website. We can also delete the data. We won’t focus on the front-end part rather we will be just coding the backend for the web application.
Installing Flask
In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below.
python -m venv <name>
Once the command is done running activate the virtual environment using the command below.
<name>\scripts\activate
Now, install Flask using pip(package installer for python). Simply run the command below.
pip install Flask
Creating app.py
Once the installation is done create a file name app.py and open it in your favorite editor. To check whether Flask has been properly installed you can run the following code.
Python
from flask import Flask
app = Flask(__name__)
'''If everything works fine you will get a
message that Flask is working on the first
page of the application
'''
@app.route('/')
def check():
return 'Flask is working'
if __name__ == '__main__':
app.run()
Output:

Setting Up SQLAlchemy
Now, let’s move on to creating a database for our application. For the purpose of this article, we will be using SQLAlchemy a database toolkit, and an ORM(Object Relational Mapper). We will be using pip again to install SQLAlchemy. The command is as follows,
pip install flask-sqlalchemy
In your app.py file import SQLAlchemy as shown in the below code. We also need to add a configuration setting to our application so that we can use SQLite database in our application. We also need to create an SQLAlchemy database instance which is as simple as creating an object.
Python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
# adding configuration for using a sqlite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
# Creating an SQLAlchemy instance
db = SQLAlchemy(app)
if __name__ == '__main__':
app.run()
Creating Models
In sqlalchemy we use classes to create our database structure. In our application, we will create a Profile table that will be responsible for holding the user’s id, first name, last name, and age.
Python
from flask import Flask, request, redirect
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
# adding configuration for using a sqlite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
# Creating an SQLAlchemy instance
db = SQLAlchemy(app)
# Models
class Profile(db.Model):
# Id : Field which stores unique id for every row in
# database table.
# first_name: Used to store the first name if the user
# last_name: Used to store last name of the user
# Age: Used to store the age of the user
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(20), unique=False, nullable=False)
age = db.Column(db.Integer, nullable=False)
# repr method represents how one object of this datatable
# will look like
def __repr__(self):
return f"Name : {self.first_name}, Age: {self.age}"
if __name__ == '__main__':
app.run()
The table below explains some of the keywords used in the model class.Â
| Column | used to create a new column in the database table |
| Integer | An integer data field |
| primary_key | If set to True for a field ensures that the field can be used to uniquely identify objects of the data table. |
| String | An string data field. String(<maximum length>) |
| unique | If set to True it ensures that every data in that field in unique. |
| nullable | If set to False it ensures that the data in the field cannot be null. |
| __repr__ | Function used to represent objects of the data table. |
Creating the database
In the command line which is navigated to the project directory and virtual environment running, we need to run the following commands.Â
python
The above command will initiate a python bash in your command line where you can use further lines of code to create your data table according to your model class in your database.Â
from app import db
db.create_all()
After the commands, the response would look like something in the picture and in your project directory you will notice a new file named ‘site.db’.Â

Making Migrations in database
Install Flask-Migrate using pipÂ
pip install Flask-Migrate
Now, in your app.py add two lines, the code being as follows,Â
Python
# Import for Migrations
from flask_migrate import Migrate, migrate
# Settings for migrations
migrate = Migrate(app, db)
Now to create migrations we run the following commands one after the other.
flask db init

flask db init
flask db migrate -m "Initial migration"

flask db migrate -m “Initial migration”
flask db upgrade

flask db upgrade
Now we have successfully created the data table in our database.
Creating the Index Page Of the Application
Before moving forward and building our form let’s create an index page for our website. The HTML file is always stored inside a folder in the parent directory of the application named ‘templates’. Inside the templates folder create a file named index.html and paste the below code for now. We will go back to adding more code into our index file as we move on.
HTML
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h3>Profiles</h3>
</body>
</html>
 In the app.py add a small function that will render an HTML page at a specific route specified in app.route.Â
Python
from flask import Flask, request, redirect
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.debug = True
# adding configuration for using a sqlite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
# Creating an SQLAlchemy instance
db = SQLAlchemy(app)
# Models
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(20), unique=False, nullable=False)
age = db.Column(db.Integer, nullable=False)
def __repr__(self):
return f"Name : {self.first_name}, Age: {self.age}"
# function to render index page
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
To test whether everything is working fine you can run your application using the commandÂ
python app.py
The command will set up a local server at http://localhost:5000.
Output:

Creating HTML page for form
We will be creating an HTML page in which our form will be rendered. Create an HTML file named add_profile in your templates folder. The HTML code is as follows. The important points in the code will be highlighted as you read on.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Add Profile</title>
</head>
<body>
<h3>Profile form</h3>
<form action="/add" method="POST">
<label>First Name</label>
<input type="text" name="first_name" placeholder="first name...">
<label>Last Name</label>
<input type="text" name= "last_name" placeholder="last name...">
<label>Age</label>
<input type="number" name="age" placeholder="age..">
<button type="submit">Add</button>
</form>
</body>
</html>
Adding a function in our application to render the form page
In our app.py file, we will add the following function. At route or site path ‘http://localhost:5000/add_data’ the page will be rendered.Â
Python
@app.route('/add_data')
def add_data():
return render_template('add_profile.html')
Â
To check whether the code is working fine or not, you can run the following command to start the local server.Â
python app.py
Now, visit http://localhost:5000/add_data and you will be able to see the form.
Output:Â

To add data to the database we will be using the “POST” method. POST is used to send data to a server to create/update a resource. In flask where we specify our route that is app.route we can also specify the HTTP methods there. Then inside the function, we create variables to store data and use request objects to procure data from the form.Â
Note: The name used in the input tags in the HTML file has to be the same one that is being been used in this function,
For example, Â
<input type="number" name="age" placeholder="age..">
“age” should also be used in the python function as,Â
age = request.form.get("age")Then we move on to create an object of the Profile class and store it in our database using database sessions.Â
Python
# function to add profiles
@app.route('/add', methods=["POST"])
def profile():
# In this function we will input data from the
# form page and store it in our database.
# Remember that inside the get the name should
# exactly be the same as that in the html
# input fields
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
age = request.form.get("age")
# create an object of the Profile class of models
# and store data as a row in our datatable
if first_name != '' and last_name != '' and age is not None:
p = Profile(first_name=first_name, last_name=last_name, age=age)
db.session.add(p)
db.session.commit()
return redirect('/')
else:
return redirect('/')
Once the function is executed it redirects us back to the index page of the application.
Display data on Index Page
On our index page now, we will be displaying all the data that has been stored in our data table. We will be using ‘Profile.query.all()‘ to query all the objects of the Profile class and then use Jinja templating language to display it dynamically on our index HTML file.
Update your index file as follows. The delete function will be written later on in this article. For now, we will query all the data from the data table and display it on our home page.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h3>Profiles</h3>
<a href="/add_data">ADD</a>
<br>
<table>
<thead>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>#</th>
</thead>
{% for data in profiles %}
<tbody>
<td>{{data.id}}</td>
<td>{{data.first_name}}</td>
<td>{{data.last_name}}</td>
<td>{{data.age}}</td>
<td><a href="/delete/{{data.id}}" type="button">Delete</a></td>
</tbody>
{% endfor%}
</table>
</body>
</html>
Â
We loop through every object in profiles that we pass down to our template in our index function and print all its data in a tabular form. The index function in our app.py is updated as follows.Â
Python
@app.route('/')
def index():
# Query all data and then pass it to the template
profiles = Profile.query.all()
return render_template('index.html', profiles=profiles)
Deleting data from our database
To delete data we have already used an anchor tag in our table and now we will just be associating a function with it.
Python
@app.route('/delete/<int:id>')
def erase(id):
# Deletes the data on the basis of unique id and
# redirects to home page
data = Profile.query.get(id)
db.session.delete(data)
db.session.commit()
return redirect('/')
The function queries data on the basis of id and then deletes it from our database.
Complete Code
The entire code for app.py, index.html, and add-profile.html has been given.Â
app.py
Python
from flask import Flask, request, redirect
from flask.templating import render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, migrate
app = Flask(__name__)
app.debug = True
# adding configuration for using a sqlite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
# Creating an SQLAlchemy instance
db = SQLAlchemy(app)
# Settings for migrations
migrate = Migrate(app, db)
# Models
class Profile(db.Model):
# Id : Field which stores unique id for every row in
# database table.
# first_name: Used to store the first name if the user
# last_name: Used to store last name of the user
# Age: Used to store the age of the user
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(20), unique=False, nullable=False)
age = db.Column(db.Integer, nullable=False)
# repr method represents how one object of this datatable
# will look like
def __repr__(self):
return f"Name : {self.first_name}, Age: {self.age}"
# function to render index page
@app.route('/')
def index():
profiles = Profile.query.all()
return render_template('index.html', profiles=profiles)
@app.route('/add_data')
def add_data():
return render_template('add_profile.html')
# function to add profiles
@app.route('/add', methods=["POST"])
def profile():
# In this function we will input data from the
# form page and store it in our database. Remember
# that inside the get the name should exactly be the same
# as that in the html input fields
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
age = request.form.get("age")
# create an object of the Profile class of models and
# store data as a row in our datatable
if first_name != '' and last_name != '' and age is not None:
p = Profile(first_name=first_name, last_name=last_name, age=age)
db.session.add(p)
db.session.commit()
return redirect('/')
else:
return redirect('/')
@app.route('/delete/<int:id>')
def erase(id):
# deletes the data on the basis of unique id and
# directs to home page
data = Profile.query.get(id)
db.session.delete(data)
db.session.commit()
return redirect('/')
if __name__ == '__main__':
app.run()
index.htmlÂ
HTML
<!DOCTYPE html>
<html>
<head>
<title>Index Page</title>
</head>
<body>
<h3>Profiles</h3>
<a href="/add_data">ADD</a>
<br>
<table>
<thead>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>#</th>
</thead>
{% for data in profiles %}
<tbody>
<td>{{data.id}}</td>
<td>{{data.first_name}}</td>
<td>{{data.last_name}}</td>
<td>{{data.age}}</td>
<td><a href="/delete/{{data.id}}" type="button">Delete</a></td>
</tbody>
{% endfor%}
</table>
</body>
</html>
add_profile.htmlÂ
HTML
<!DOCTYPE html>
<html>
<head>
<title>Add Profile</title>
</head>
<body>
<h3>Profile form</h3>
<form action="/add" method="POST">
<label>First Name</label>
<input type="text" name="first_name" placeholder="first name...">
<label>Last Name</label>
<input type="text" name= "last_name" placeholder="last name...">
<label>Age</label>
<input type="number" name="age" placeholder="age..">
<button type="submit">Add</button>
</form>
</body>
</html>
Output:
Â
Similar Reads
Flask Tutorial
This Flask tutorial is the latest and comprehensive guide designed for beginners and professionals to learn Python Web Framework Flaskone, one of the most popular Python-based web frameworks. Whether you are a beginner or an experienced developer, this tutorial is specially designed to help you lear
8 min read
Flask Setup & Installation
Flask Quick Start
Flask - (Creating first simple application)
Building a webpage using python.There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program wit
6 min read
How to Run a Flask Application
The backend server Flask was created fully in Python. It is a framework made up of Python modules and packages. With its characteristics, it is a lightweight Flask application that speeds up the development of backend apps. We will learn how to execute a Flask application in this tutorial. Run Flask
4 min read
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL ("/") is associated with the root URL. So if our site's
3 min read
Flask - HTTP Method
In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Here, we will understand the concept of HTTP, GET, and HTTP POST, and then we will the example and implement each in Flask. Before starting let's understand the basic terminology: GET: to request d
8 min read
Flask - Variable Rule
In this article, we will discuss Flask-Variable Rule using Python. Flask is a microweb framework written in Python it is classified as a micro framework because it doesn't require particular tools or libraries, and it has no database abstraction layer form validation or any other components where pr
4 min read
Redirecting to URL in Flask
Flask is a backend server that is built entirely using Python. It is a framework that consists of Python packages and modules. It is lightweight which makes developing backend applications quicker with its features. In this article, we will learn to redirect a URL in the Flask web application. Redir
3 min read
Python Flask - Redirect and Errors
We'll discuss redirects and errors with Python Flask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server,
4 min read
How to Change Port in Flask app
In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
1 min read
Changing Host IP Address in Flask
In this article, we will cover how we can change the host IP address in Flask using Python. The host IP address is the network address that identifies a device on a network. In the context of a Flask application, the host IP address is the address that the application listens to for incoming request
2 min read
Serve Templates and Static Files in Flask
Flask Rendering Templates
Flask is a backend web framework based on the Python programming language. It basically allows the creation of web applications in a Pythonic syntax and concepts. With Flask, we can use Python libraries and tools in our web applications. Using Flask we can set up a web server to load up some basic H
13 min read
CSRF Protection in Flask
Let's see how you can manually protect your data using CSRF protection by doing a mini-project in Flask. In this, we will have to create a webpage containing 2 forms using Python one of them is having protection. By creating forms like these we can easily see the results and advantages of using CSRF
3 min read
Template Inheritance in Flask
Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc. So instead of making same footer and navigation bar in all webpages separately , w
2 min read
Placeholders in jinja2 Template - Python
Web pages use HTML for the things that users see or interact with. But how do we show things from an external source or a controlling programming language like Python? To achieve this templating engine like Jinja2 is used. Jinja2 is a templating engine in which placeholders in the template allow wri
5 min read
How to serve static files in Flask
Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask. S
5 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uplo
7 min read
How to Upload File in Python-Flask
File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
2 min read
Upload Multiple files with Flask
In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request
2 min read
Flask - Message Flashing
In this article, we will discuss Flask - Message Flashing. As we know best Graphical User Interface provides feedback to a user when users interact, as an example, we know that desktop applications use the messages box or JS for an alert purpose. generating like same informative message is easy to d
6 min read
Create Contact Us using WTForms in Flask
WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms. Advantages of WT-FORM:We don't have to worry about validators.Avoidance of Cross-S
3 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language donât need any external library to import and offers a native library to send emails- âSMTP libâ. âsmtplibâ creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around
3 min read
User Registration, Login, and Logout in Flask
How To Add Authentication to Your App with Flask-Login
Whether it is building a simple blog or a social media site, ensuring user sessions are working correctly can be tricky. Fortunately, Flask-Login provides a simplified way of managing users, which includes easily logging in and out users, as well as restricting certain pages to authenticated users.
9 min read
Add User and Display Current Username in Flask
In this article, we'll talk about how to add a User and Display the Current Username on a Flask website. When we log in using our username and password, we will be taken to the profile page where we can see the welcome message and the username we created during registration. When additional users re
9 min read
Password Hashing with Bcrypt in Flask
In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used t
2 min read
How to store username and password in Flask
We'll discuss how to save a Username and password on a Flask website in this article. We may view the welcome message and the username we chose when registering on the profile page after logging in with our username and password. The names of subsequent users who sign up using the login information
9 min read
Flask - Role Based Access Control
Flask is a  micro-framework written in Python. It is used to create web applications using Python. Role-based access control means certain users can access only certain pages. For instance, a normal visitor should not be able to access the privileges of an administrator. In this article, we will see
14 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the ser
4 min read
Flask Cookies
Flask is a lightweight, web development framework built using python language. Generally, for building websites we use HTML, CSS and JavaScript but in flask the python scripting language is used for developing the web-applications. To know more about Flask and how to run an application in Flask: Fla
5 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Represent
3 min read
Define and Access the Database in Flask
Flask Deployment and Error Handling
Python Flask Projects with Source Code (Beginners to Advanced)
Flask, a Python web application framework, was created by Armin Ronacher. Known for its lightweight and efficient nature, Flask is designed for quick starts and accommodates complex applications. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. In this article, weâve curated a li
4 min read