Flask-Web-App-Tutorial icon indicating copy to clipboard operation
Flask-Web-App-Tutorial copied to clipboard

TypeError: create_all() got an unexpected keyword argument 'app'

Open nadeembu opened this issue 3 years ago • 14 comments

Here is the code.

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

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

def create_app(): app = Flask(name) app.config['SECRET_KEY'] = 'kjshkjdhjs' 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)

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))

return app

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

Could someone help with this please? Thanks.

nadeembu avatar Oct 26 '22 05:10 nadeembu

Hello, have same issue... Traceback (most recent call last): File "f:\munca\flasking\main.py", line 3, in app = create_app() File "f:\munca\flasking\website_init_.py", line 24, in create_app create_database(app) File "f:\munca\flasking\website_init_.py", line 30, in create_database db.create_all(app=app) TypeError: SQLAlchemy.create_all() got an unexpected keyword argument 'app'

Can anyone help us?

raychone avatar Oct 26 '22 12:10 raychone

Here is the code.

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

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

def create_app(): app = Flask(name) app.config['SECRET_KEY'] = 'kjshkjdhjs' 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)

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))

return app

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

Could someone help with this please? Thanks.

Hello, you need to change this:

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

with this:

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

raychone avatar Oct 26 '22 18:10 raychone

amazing!!! Works perfect now!! Thank you very much!! Haven't got a clue what it means, but I will look it up.

nadeembu avatar Oct 26 '22 18:10 nadeembu

cheers! good luck! when this repets just ask and someone will sure help.

raychone avatar Oct 26 '22 18:10 raychone

@raychone thank you, this works 🙂

A polite suggestion for the future, when posting code, use code blocks to make it easy to read and copy. 😬

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

TurboCoder13 avatar Oct 31 '22 15:10 TurboCoder13

Thank you. I discovered the <> code block button when I posted another error I had. :)

nadeembu avatar Nov 01 '22 05:11 nadeembu

Here is the code. from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import path from flask_login import LoginManager db = SQLAlchemy() DB_NAME = "database.db" def create_app(): app = Flask(name) app.config['SECRET_KEY'] = 'kjshkjdhjs' 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)

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))

return app

def create_database(app): if not path.exists('website/' + DB_NAME): db.create_all(app=app) print('Created Database!') Could someone help with this please? Thanks.

Hello, you need to change this:

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

with this:

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

Thanks very much it's working

ndongchrist avatar Nov 05 '22 07:11 ndongchrist

Guys, I changed the:

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

for the:

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

And now the problem it gives me is:

app = create_app() File "c:\Users\Gabrango\Flask website tutorial\website_init_.py", line 22, in create_app

create_database(app) File "c:\Users\Gabrango\Flask website tutorial\website_init_.py", line 29, in create_database db.create_all() File

"C:\Users\Gabrango\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask_sqlalchemy\extension.py", line 868, in create_all
self._call_for_binds(bind_key, "create_all") File

"C:\Users\Gabrango\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask_sqlalchemy\extension.py", line 846, in _call_for_binds raise sa.exc.UnboundExecutionError(message) from None sqlalchemy.exc.UnboundExecutionError: 'SQLALCHEMY_DATABASE_URI' config is not set. Bind key 'None' is not in 'SQLALCHEMY_BINDS' config.

Help pleaseeee

Gabrango avatar Dec 04 '22 15:12 Gabrango

Hi There, I'm a newbie to this, but lookin at the final error. Do you have this line set in the create_app function?

app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'

Here is the complete code for that function.

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'kjshkjdhjs'
    # Define the location of our sqlite database.
    # which is within our website folder.
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    # Initialize the database and give it our flask app
    db.init_app(app)`

Here is the complete code I have in my init.py file. You could copy and paste it and see if it fixes it.

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


# Define a new database and give it the name databasbe.db
db = SQLAlchemy()
DB_NAME = "database.db"


def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'kjshkjdhjs'
    # Define the location of our sqlite database.
    # which is within our website folder.
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    # Initialize the database and give it our flask app
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    # Importing the functions in the models.py file into this file.
    # This file needs to run before we initialize the database,
    # so the classes get defined and we can then use them.
    from .models import User, Note

    create_database(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

# A function to create our database.


def create_database(app):
    # Check if the database already exist.
    if not path.exists('website/' + DB_NAME):
        with app.app_context():
            # Create our database if it doesn't exist.
            db.create_all()
            print('Created Database!')`

nadeembu avatar Dec 04 '22 16:12 nadeembu

Thanks a lot!!!!!

I actually had the app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}', but reading your comment I realized that I did not have the db.init_app(app)

Thank you bro

Gabrango avatar Dec 04 '22 16:12 Gabrango

YAY!!! You are the first person I managed to help!!!! Whoop Whoop!!!!! :)

nadeembu avatar Dec 04 '22 16:12 nadeembu

I will also steal your annotations, it looks like a very helpful way to do the tutorial!

Gabrango avatar Dec 04 '22 16:12 Gabrango

oh my goodness, raychone, you literally saved my insanity - this helped me finally figure out the issue. I was finding this same sort of thing on the documentation on flask, however, I was not sure where that change had to be placed - thank you!!

(by the way, this is the fix in case you had not seen it or not know what I am talking about)

FROM RAYCHONE

Hello, you need to change this:

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

with this:

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

78wesley, a-abukar, and technicallyoutdoors reacted with thumbs up emoji

technicallyoutdoors avatar Jan 11 '23 21:01 technicallyoutdoors

here is the real answer ... i followed all the things everyone said but no one told me the database would be created in the folder called instance

https://github.com/techwithtim/Flask-Web-App-Tutorial/issues/79#issuecomment-1269236431

This is because flask-sqlalchemy update in 3.0 look up here https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/quickstart/#create-the-tables

update your code to this

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

your database will created in folder `\instance\database.db'

quantfreedom avatar Jan 15 '23 01:01 quantfreedom