pythonflasksqlalchemyflask-sqlalchemy

I cannot create table using SQLAlchemy


I have a table with a few columns in an empty database and then db.create_all() with with app.app_context()but when I run the code, the database is still empty and there are no tables. CODE EDITOR: Visual Studio Code, DATABASE EDITOR: DB Browser for SQLite

Here is my code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import Integer, String, Float

app = Flask(__name__)

class Base(DeclarativeBase):
    pass

app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///new-books-collection.db"

db = SQLAlchemy(model_class=Base)
db.init_app(app)

class Book(db.Model):
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    title: Mapped[str] = mapped_column(String(250), unique=True, nullable=False)
    author: Mapped[str] = mapped_column(String(250), nullable=False)
    rating: Mapped[float] = mapped_column(Float, nullable=False)


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

But when I run it, the datasource is still blank with no tables.


Solution

  • Turns out, I was checking the wrong place, instead of checking the database at /python/instance, I was checking the manually created one at /python/.

    To change the instance folder to /python, I just changed the flask initialization to app = Flask(__name__, instance_path='/python').