1

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.

8
  • Are you sure you have opened the created database file in the instance folder to check if the tables are there? Commented Jun 5 at 21:10
  • I don't quite understand what instance folder means, but here is the path of everything, /python/main.py (my code), /python/new-books-collection.db (database), /python/venv/lib/python3.12/site-packages/... (libraries). Commented Jun 5 at 21:17
  • The database isn't located directly in your project directory. When the database is created, a subdirectory is created within your folder where the file is stored. print(app.instance_path) shows you where to look after you've started the application. Commented Jun 5 at 21:24
  • Oh, the app.instance_path printed python/instance, Commented Jun 5 at 21:28
  • There should be a file named new-books-collection.db containing all the tables. Commented Jun 5 at 21:29

1 Answer 1

0

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').

Sign up to request clarification or add additional context in comments.

2 Comments

You should keep the database in the instance folder, as that is part of the directory structure that flask relies on. For detailed information see the Flask Tutorial.
Thank you, if I ever face an error for that, I will move everything to an instance folder. But for now, I would prefer to keep the instance at /python

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.