[Python] I cannot create table using SQLAlchemy

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página