English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Performing CRUD operations on the database using raw SQL in a Flask web application may be tedious. Instead, the Python toolkit SQLAlchemy is a powerful OR mapper that provides all the functionality and flexibility of SQL to application developers. Flask-SQLAlchemy is a Flask extension that adds SQLAlchemy support to Flask applications.
What is ORM (Object-Relational Mapping)?
Most programming language platforms are object-oriented. On the other hand, data in RDBMS servers are stored in table form. Object-relational mapping is a technology that maps object parameters to the underlying RDBMS table structure. The ORM API provides methods for executing CRUD operations without writing raw SQL statements.
In this section, we will learn to use Flask-Use SQLAlchemy's ORM technology to build a small web application.
No.1Step - Install Flask-SQLAlchemy extension.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 pip install flask-sqlalchemy
No.2Step - It is necessary to import the SQLAlchemy class from this module.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from flask_sqlalchemy import SQLAlchemy
No.3Step - Now create a Flask application object and set the URI for the database to be used.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
No.4Step - Then create an object of the SQLAlchemy class using the application object as a parameter. This object contains auxiliary functions for ORM operations. It also provides a parent model class that uses its declared user-defined models. In the following code snippet, a student model is created.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 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): self.name = name self.city = city self.addr = addr self.pin = pin
No.5Step - To create/Please run the create_all() method using the database mentioned in the URI.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 db.create_all()
The SQLAlchemy Session object manages all persistence operations of ORM objects.
The following session methods perform CRUD operations -
db.session.add(model_object) - Insert a record into the mapping table db.session.delete(model_object) - Delete records from the table model.query.all() - Retrieve all records from the table (corresponding to SELECT query).
You can use the filter attribute to apply filters to the retrieved record set. For example, to retrieve records from the 'students' table where 'city' = 'Haikou', use the following statement -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 Students.query.filter_by(city='Haikou').all()
With so much background knowledge, now we will provide view functions for our application to add student data.
The entry point of the application is bound to URL => '/The 'show_all()' function of 'show_all.html' sends the record set of students as a parameter to the HTML template. The server-side code in the template presents the records in the form of an HTML table.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 @app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all())
The HTML script of the template ( show_all.html)like this -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask example</title> </head> <body> <h3> <a href="{{ url_for('show_all') }}">Student List</a> - Flask SQLAlchemy Example</a> </h3> <hr/> {%- for message in get_flashed_messages() %} {{ message }} {%- endfor %} <h3>Student (<a href="{{ url_for('new') }}">Add</a> </a>)/h3> <table> <thead> <tr> <th>Name</th>/th> <th>City</th>/th> <th>Address</th>/th> <th>Pin</th>/th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td>/td> <td>{{ student.city }}</td>/td> <td>{{ student.addr }}</td>/td> <td>{{ student.pin }}</>/td> </tr> {% endfor %} </tbody> </table> </body> </html>
The above page includes a link to the URL:/new hyperlinks to the new() function mapping. Clicking it will open a student information form. The data is published to the same URL via the POST method.
Template file: new.html The code is as follows -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask example</title> </head> <body> <h3>Student Information< - Flask SQLAlchemy example</h3> <hr/> {%- for category, message in get_flashed_messages(with_categories=True) %} <div class="alert alert-danger"> {{ message }} </div> {%- 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">Address</label><br> <textarea name="addr" placeholder="addr">/><br> <label for="PIN">City</label><br> <input type="text" name="pin" placeholder="pin"> /><br> <input type="submit" value="submit"> /> </form> </body> </html>
When the HTTP method is POST, the form data will be inserted into the students table, and the application will return to the homepage displaying the data.
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 @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') 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')
Below is the complete application code( app.py)。
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : www.oldtoolbag.com # Date : 2020-08-08 from flask import Flask, request, flash, url_for, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' app.config['SECRET_KEY'] = "random string" 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): self.name = name self.city = city self.addr = addr self.pin = pin @app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all()) @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') else: student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) print(student) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.run(debug=True)
Run the script from the Python shell and enter the following in the browser: http://localhost:5/ “ -
Click “ Add”Link to open the student information form.
Fill in the form and submit, the homepage will list the submitted data. After the operation, you will see the output as shown below.