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'
CodePudding user response:
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.