Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy db.create_all() got an unexpected keyword argument 'app'

I'm following a tutorial for creating a Flask app with Flask-SQLAlchemy. However, it has started raising an error when creating the database. How do I create the database?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
    db.init_app(app)

    from . import models

    create_database(app)
    return app

def create_database(app):
    if not path.exists("website/project.db"):
        db.create_all(app=app)
        print("created database")

The line db.create_all(app=app) gives me this error:

SQLAlchemy.create_all() got an unexpected keyword argument 'app'
like image 359
Tatia - Avatar asked Sep 12 '25 15:09

Tatia -


1 Answers

Flask-SQLAlchemy 3 no longer accepts an app argument to methods like create_all. Instead, it always requires an active Flask application context.

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
    db.init_app(app)

    from . import models

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

    return app

There is no need for that create_database function. SQLAlchemy will already not overwrite an existing file, and the only time the database wouldn't be created is if it raised an error.

like image 65
davidism Avatar answered Sep 15 '25 06:09

davidism