Flask SQLAlchemy

Estimated reading: 4 minutes 761 views

Flask SQLAlchemy (with Examples)

Using raw SQL in the Flask Web application to perform CRUD operations on the database can be cumbersome.

Instead, SQLAlchemy, the Python Toolkit is a powerful OR Mapper, which provides application developers with the full functionality and flexibility of SQL.

Flask-SQLAlchemy is a Flask extension that adds support for SQLAlchemy to the Flask application.

What is ORM?

ORM is short for Object Relation Mapping (sometimes Object Relationship Mapping).

  • Most programming language platforms are object-oriented.
  • the data in the RDBMS server is stored in tables.

Object-relational mapping is a technique that maps object parameters to the structure of a layer RDBMS table. The ORM API provides a way to perform CRUD operations without writing raw SQL statements.

Flask SQLAlchemy


In this section, we will study the ORM technology of Flask-SQLAlchemy and build a small web application.

Step 1 – Install the Flask-SQLAlchemy extension.

					pip install flask-sqlalchemy

Step 2 – You need to import the SQLAlchemy class from this module.

					from flask_sqlalchemy import SQLAlchemy


Step 3 – Now create a Flask application object and set the URI for the database to use.

					app = Flask (__name__)
app.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'


Step 4 – then use the application object as a parameter to create an object of class SQLAlchemy.The object contains an auxiliary function for the ORM operation.It also provides a parent Model class that uses it to declare a user-defined model.In the code snippet below, the studients model is created.

					db = SQLAlchemy(app)
class students(db.Model):
   id = db.Column('student_id', db.Integer, primary_key = True)
   name = db.Column(db.String(100))
   city = db.Column(db.String(50))  
   addr = db.Column(db.String(200))
   pin = db.Column(db.String(10))

def __init__(self, name, city, addr,pin): = name = city
   self.addr = addr = pin

Step 5 – To create/use the database mentioned in the URI, run the create_all() method.



SQLAlchemy’s Session object manages all persistence operations for ORM objects.

The following session method performs CRUD operations:

					# Inserts records into a mapping table
db.session.add (model object)
					# delete records from a table
db.session.delete (model object)

					# retrieves all records (corresponding to SELECT queries) from the table.
model.query.all ()

You can apply filters to the retrieved record set by using the filter attribute.For example, to retrieve records for city = ‘Tokyo’ in student tables, use the following statement:

					students.query.filter_by(city = ’Tokyo’).all()

Show all

The entry point of the application is the show_all () function that is bound to the ‘ /‘ URL.The record set of the student table is sent as a parameter to the HTML template.The server-side code in the template renders the record as an HTML table.

def show_all():
   return render_template('show_all.html', students = students.query.all() )

The HTML script for the template (‘show_all.html ‘) is as follows:

					<!DOCTYPE html>
<html lang = "en">
         <a href = "{{ url_for('show_all') }}">Comments - Flask 
            SQLAlchemy example</a>
      {%- for message in get_flashed_messages() %}
         {{ message }}
      {%- endfor %}
      <h3>Students (<a href = "{{ url_for('new') }}">Add Student
            {% for student in students %}
                  <td>{{ }}</td>
                  <td>{{ }}</td>
                  <td>{{ student.addr }}</td>
                  <td>{{ }}</td>
            {% endfor %}

New record

The web page contains a hyperlink to the ‘/new’ URL mapping new () function.When clicked, the Student Information form opens. Data is published to the same URL in the POST method.

The view new.html contains:

					<!DOCTYPE html>
      <h3>Students - Flask SQLAlchemy example</h3>
      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {{ message }}
      {%- endfor %}
      <form action = "{{ request.path }}" method = "post">
         <label for = "name">Name</label><br>
         <input type = "text" name = "name" placeholder = "Name" /><br>
         <label for = "email">City</label><br>
         <input type = "text" name = "city" placeholder = "city" /><br>
         <label for = "addr">addr</label><br>
         <textarea name = "addr" placeholder = "addr"></textarea><br>
         <label for = "PIN">City</label><br>
         <input type = "text" name = "pin" placeholder = "pin" /><br>
         <input type = "submit" value = "Submit" />


When the http method is detected as POST, the form data is added to the student table, and the application is returned to the home page of the display adding data.

					@app.route('/new', methods = ['GET', 'POST'])
def new():
   if request.method == 'POST':
      if not request.form['name'] or not request.form['city'] or not request.form['addr']:
         flash('Please enter all the fields', 'error')
         student = students(request.form['name'], request.form['city'],
            request.form['addr'], request.form['pin'])
         flash('Record was successfully added')
         return redirect(url_for('show_all'))
   return render_template('new.html')

Leave a Comment

Share this Doc