Data Modeling in Flask

This chapter covers one of the most important aspects of any application, that is, the interaction with database systems. This will take us through how Flask can connect to database systems, define models, and query the databases for the retrieval and feeding of data. Flask has been designed to be flexible enough to support any database. The simplest way would be to use the direct SQLite3 package, which is a DB-API 2.0 interface and does not give an actual object-relational mapper (ORM). Here, we need to use SQL queries to talk with the database. This approach is not recommended for large projects as it can eventually become a nightmare to maintain the application. Also, with this approach, the models are virtually non-existent and everything happens in the view functions, where we write queries to interact with the database.

In this chapter, we will talk about creating an ORM layer for our Flask applications with SQLAlchemy for relational database systems, which is recommended and widely used for applications of any size. Also, we will have a glance over how to write a Flask app with the NoSQL database system.

ORM refers to ORM and implies how our application's data models store and deal with data at a conceptual level. A powerful ORM makes the designing and querying of business logic easy and streamlined.

In this chapter, we will cover the following recipes:

  • Creating an SQLAlchemy DB instance
  • Creating a basic product model
  • Creating a relational category model
  • Migrating databases using Alembic and Flask-Migrate
  • Indexing model data with Redis
  • Opting for the NoSQL way with MongoDB