0
0
Flaskframework~30 mins

Flask-SQLAlchemy setup - Mini Project: Build & Apply

Choose your learning style9 modes available
Flask-SQLAlchemy setup
📖 Scenario: You are building a simple web app to store book information. You want to save book titles and authors in a database using Flask and SQLAlchemy.
🎯 Goal: Create a Flask app with SQLAlchemy configured, define a Book model, and set up the database connection.
📋 What You'll Learn
Create a Flask app instance named app
Configure the app with SQLALCHEMY_DATABASE_URI set to sqlite:///books.db
Create a SQLAlchemy object named db linked to the app
Define a Book model with id, title, and author fields
Ensure the id is the primary key and an integer
Use db.Column and appropriate types for fields
💡 Why This Matters
🌍 Real World
Flask with SQLAlchemy is commonly used to build web apps that need to store and manage data in databases.
💼 Career
Understanding how to set up Flask with SQLAlchemy is essential for backend web development roles using Python.
Progress0 / 4 steps
1
Create Flask app instance
Write code to import Flask from flask and create a Flask app instance called app.
Flask
Need a hint?

Use Flask(__name__) to create the app.

2
Configure database URI
Add a configuration line to app.config setting SQLALCHEMY_DATABASE_URI to 'sqlite:///books.db'.
Flask
Need a hint?

Use app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db'.

3
Create SQLAlchemy object
Import SQLAlchemy from flask_sqlalchemy and create a db object by passing app to SQLAlchemy.
Flask
Need a hint?

Use db = SQLAlchemy(app) after importing.

4
Define Book model
Define a class Book that inherits from db.Model. Add three fields: id as an integer primary key, title as a string of max length 100, and author as a string of max length 50. Use db.Column and appropriate types.
Flask
Need a hint?

Define Book class with fields using db.Column and types.