0
0
Flaskframework~30 mins

Creating tables (db.create_all) in Flask - Try It Yourself

Choose your learning style9 modes available
Creating Tables with Flask and SQLAlchemy
📖 Scenario: You are building a simple web app to store information about books in a library. You want to create a database table to hold the book details.
🎯 Goal: Create a Flask app with SQLAlchemy that defines a Book model and creates the corresponding table in the database using db.create_all().
📋 What You'll Learn
Create a Flask app instance named app
Create a SQLAlchemy database instance named db linked to app
Define a Book model with columns id (integer primary key), title (string), and author (string)
Use db.create_all() to create the tables in the database
💡 Why This Matters
🌍 Real World
Creating tables is the first step in building web apps that store data persistently, like user info, products, or posts.
💼 Career
Understanding how to define models and create tables is essential for backend web development roles using Flask and SQLAlchemy.
Progress0 / 4 steps
1
Set up Flask app and SQLAlchemy
Create a Flask app instance called app and configure it with SQLALCHEMY_DATABASE_URI set to 'sqlite:///library.db'. Then create a SQLAlchemy instance called db linked to app.
Flask
Need a hint?

Use Flask(__name__) to create the app. Set app.config['SQLALCHEMY_DATABASE_URI'] to the SQLite file path. Then create db = SQLAlchemy(app).

2
Define the Book model
Define a class called Book that inherits from db.Model. Add three columns: id as an integer primary key, title as a string of max length 100, and author as a string of max length 50.
Flask
Need a hint?

Define a class Book inheriting from db.Model. Use db.Column to define each column with the right type and primary key for id.

3
Create the tables in the database
Call db.create_all() to create the tables in the database based on the models defined.
Flask
Need a hint?

Use db.create_all() to create tables for all models in the database.

4
Run the Flask app
Add the code to run the Flask app by calling app.run() inside the if __name__ == '__main__': block.
Flask
Need a hint?

Use the standard Python block if __name__ == '__main__': and call app.run() inside it to start the Flask server.