pythonflasksqlalchemyflask-sqlalchemy

Building a database using SQLAchemy


I'm kind of stuck on making a database for my Flask application using SQLAlchemy. infact I'm watching a tutorial for Flask apps; everything was ok until I've reached this error: SQLAlchemy.create_all() got an unexpected argument: 'app'

here's the code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path

db = SQLAlchemy()
DB_NAME = 'database.db'

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'AmirMohammad Purzahed'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)
    
    from .views import views
    from .auth import auth
    
    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')
    
    from .models import User, Note
    
    create_database(app)
    
    return app

def create_database(app):
    if not path.exists('website/' + DB_NAME):
        db.create_all(app=app)
        print('Created Database!')

Solution

  • Well you'll obviously need to remove the app argument from your create_all(). But to make sure the app context is available when create_all() is called, you'll have to wrap create_database() with with app.app_context():

    # ... Above stays the same ...
    
        with app.app_context():
            create_database()
    
        return app
    
    def create_database():
        if not path.exists('website/' + DB_NAME):
            db.create_all()
            print('Created Database!')
    

    Also remove the app argument from your function, it's not needed.


    See Flask-SQLAlchemy application context documentation (3.1.x) for more info.