As you've seen, writing SQL commands are complicated and error-prone. It would be much better if we could just write Python code and get the compiler to help us spot typos and errors in our code. That's why SQLAlchemy was created.

SQLAlchemy is defined as an ORM Object Relational Mapping library. This means that it's able to map the relationships in the database into Objects. Fields become Object properties. Tables can be defined as separate Classes and each row of data is a new Object. This will make more sense after we write some code and see how we can create a Database/Table/Row of data using SQLAlchemy.

1. Comment out all the existing code where we create an SQLite database directly using the sqlite3 module.

2. Install the required packages flask and flask_sqlalchemy and import the Flask and SQLAlchemy classes from each.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


CHALLENGE: Use the SQLAlchemy documentation to figure out how to do everything we did in the commented out code but this time using SQLAlchemy.

Requirements:

  • Create an SQLite database called new-books-collection.db

  • Create a table in this database called books.

  • The books table should contain 4 fields: id, title, author and rating. The fields should have the same limitations as before e.g. INTEGER/FLOAT/VARCHAR/UNIQUE/NOT NULL etc.

  • Create a new entry in the books table that consists of the following data:

id: 1

title: "Harry Potter"

author: "J. K. Rowling"

review: 9.3


HINT 1: The URL for your database should be "sqlite:///new-books-collection.db"

HINT 2: Don't if you get a deprecation warning in the console that's related to SQL_ALCHEMY_TRACK_MODIFICATIONS

You can silence it with

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

HINT 3: You can always check the database using DB Browser.


SOLUTION