Go back to the home page and click ‘Show List’link. The table showing the sample data will be displayed.
55 Using raw SQL in Flask web applications to perform CRUD operations on database can be tedious. Instead, SQLAlchemy, a Python toolkit is a powerful OR Mapperthat gives application developers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask extension that adds support for SQLAlchemy to your Flask application. What is ORM (Object Relation Mapping)? Most programming language platforms are object oriented. Data in RDBMS servers on the other hand is stored as tables. Object relation mapping is a technique of mapping object parameters to the underlying RDBMS table structure. An ORM API provides methods to perform CRUD operations without having to write raw SQL statements. In this section, we are going to study the ORM techniques of Flask-SQLAlchemy and build a small web application. Step 1: Install Flask-SQLAlchemy extension. pip install flask-sqlalchemy Step 2: You need to import SQLAlchemy class from this module. from flask_sqlalchemy import SQLAlchemy Step 3: Now create a Flask application object and set URI for the database to be used. app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///students.sqlite3' Step 4:Then create an object of SQLAlchemy class with application object as the parameter. This object contains helper functions for ORM operations. It also provides a parent Model class using which user defined models are declared. In the snippet below, a studentsmodel 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): self.name = name self.city = city 21. Flask –SQLAlchemy
Flask 56 self.addr = addr self.pin = pin Step 5: To create / use database mentioned in URI, run the create_all()method. db.create_all() The Sessionobject of SQLAlchemymanages all persistence operations of ORMobject. The following session methods perform CRUD operations: db.session.add(model object) : inserts a record into mapped table db.session.delete(model object) : deletes record from table model.query.all(): retrieves all records from table (corresponding to SELECT query). You can apply a filter to the retrieved record set by using the filter attribute. For instance, in order to retrieve records with city=’Hyderabad’in students table, use following statement: Students.query.filter_by(city=’Hyderabad’).all()With this much of background, now we shall provide view functions for our application to add a student data. The entry point of the application is show_all() function bound to ‘/’URL. The Record set of students table is sent as parameter to the HTML template. The Server side code in the template renders the records in HTML table form.