Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære SQLAlchemy Set Up | Database and Models
Professional Web API with Flask

book
SQLAlchemy 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:

python
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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:

python
# Import the database from our package
from db import db

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

python
def create_app():

app = Flask(__name__)

app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")

return app

Add new database-related parameters:

python
import os
from flask import Flask
from dotenv import load_dotenv

from db import db


load_dotenv()


def create_app():

app = Flask(__name__)

app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL", "sqlite:///db.sqlite3")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db.init_app(app)

with app.app_context():
db.create_all()

return app


app = create_app()

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 1
some-alt