Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
SQLAlchemy Set Up
course content

Course Content

Professional Web API with Flask

SQLAlchemy Set UpSQLAlchemy Set Up

In our previous project and course, we have gained proficiency in working with SQLAlchemy, storing our recipes in a SQLite database. SQLite is a convenient database for the development process. The transition between databases is seamless in the code, as SQLAlchemy is a highly versatile library that facilitates the connection between the application and many well-known SQL databases.

For those who prefer an interactive approach to database management and wish to see changes in real time, a desktop version of SQLite can be downloaded. If you have the Pro version of PyCharm, you can view changes in a special database window.

To download and set up SQLite on your PC, follow the link provided and select the version compatible with your operating system: SQLite Studio.

With the application installed, you can now explore the structure of your database in detail.

Connecting and Configuring the Database to Your Application

To integrate and configure the database with our application, we first need to install Flask-SQLAlchemy by running:

Next, create a new Python file named 'db.py', where we will initiate our database:

Proceed to the 'app.py' file, which contains all our configurations. After the command that initializes the application, insert several commands related to our database:

Flask Application Factory Pattern

Until now, we created the app variable (which is the Flask application) directly in app.py. Using the application factory pattern, we write a function that returns app. This allows us to pass configuration values to the function, enabling us to customize the application before it's returned. This approach is especially useful for testing and scenarios such as staging and production environments.

To implement the application factory, encapsulate the application creation code inside a function named create_app():

Add new database-related parameters:

Code Description
  • from db import db This line imports the db instance from a module named db. This db instance is typically an SQLAlchemy object that has been created in the db module. This object is responsible for all the database operations in the application.
  • def create_app(): This defines a function named create_app that will create and return a Flask application instance. The application factory pattern is a recommended Flask design pattern, especially useful for larger applications. It allows for better configuration and testing flexibility.
  • app = Flask(__name__) Inside the create_app function, a new Flask application instance is created. __name__ is passed to the Flask class to determine the root path of the application so that Flask can find resource files relative to the location of the application.
  • app.config["SECRET_KEY"] = os.getenv("SECRET_KEY") A secret key is used by Flask for securely signing the session cookie.
  • app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL", "sqlite:///db.sqlite3") The database URL for SQLAlchemy. It defaults to a local SQLite database file named db.sqlite3 if the DATABASE_URL environment variable is not set.
  • app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False When set to False, it disables the Flask-SQLAlchemy event system, improving performance.
  • db.init_app(app) This initializes the SQLAlchemy 'db' object with the Flask app. This is necessary for SQLAlchemy to work with the application.
  • with app.app_context(): db.create_all() This block temporarily pushes an application context, making the 'app' instance active. Inside this context, 'db.create_all()' is called to create all database tables based on the defined models. This only creates tables that do not already exist.
  • return app The 'create_app' function concludes by returning the configured Flask app instance.
  • app = create_app() Finally, the script calls 'create_app()' function to create and configure the Flask application instance. This instance is assigned to the variable app, making it the entry point for running the Flask application.

We introduced the DATABASE_URI parameter, allowing us to configure the application with a specific database URL obtained from the environment variables. The default value is a local SQLite file if not specified in the environment. We also added two SQLAlchemy configurations to app.config: one for the database URL (or URI) and another to enhance performance by not tracking modifications. Upon application creation, we instruct SQLAlchemy to create all necessary database tables.

Currently, no tables will appear until the application is restarted, as we have not yet defined any models.

Everything was clear?

Section 2. Chapter 1
some-alt