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.
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()
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: