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.
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
Setup
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.
1
pip install flask-sqlalchemy
Step 2 - You need to import the SQLAlchemy class from this module.
1
from flask_sqlalchemy import SQLAlchemy
Step 3 - Now create a Flask application object and set the URI for the database to use.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13
db = SQLAlchemy(app) classstudents(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): self.name = name self.city = city self.addr = addr self.pin = pin
Step 5 - To create/use the database mentioned in the URI, run the create_all() method.
1
db.create_all()
CRUD
SQLAlchemy’s Session object manages all persistence operations for ORM objects.
The following session method performs CRUD operations:
1 2
# Inserts records into a mapping table db.session.add (model object)
1 2
# delete records from a table db.session.delete (model object)
1 2
# 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:
1
students.query.filter_by(city = ’Tokyo’).all()
With so many backgrounds, now we will provide a view function for our application to add student data.
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.
1 2 3
@app.route('/') defshow_all(): return render_template('show_all.html', students = students.query.all() )
The HTML script for the template (‘show_all.html ‘) is as follows:
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@app.route('/new', methods = ['GET', 'POST']) defnew(): if request.method == 'POST': ifnot request.form['name'] ornot request.form['city'] ornot request.form['addr']: flash('Please enter all the fields', 'error') else: student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html')
SQLAlchemy Example
The complete code for the application (app.py) is given below.