Flask application, db.create_all() does not create the database

Question:

I’m new in creating Flask applications and I’m following a tutorial to quick start. I see that this question about db.create_all() is frequent, nonetheless I can’t understand why I can’t create a database.

my project structure

I’m initializing the dataset in __ init __.py as follows:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'uiasdasn moaisw eeert'
    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
    
    with app.app_context():
         db.create_all()
         db.session.commit()

    return app

while the User class is defined in models.py

from . import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    first_name = db.Column(db.String(150))

Can you tell me what I’m doing wrong?

Asked By: Marco B

||

Answers:

Well, if you’re showing the complete init.py file, you’re missing execute the function 🙂

You should add something like:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'uiasdasn moaisw eeert'
    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
    
    with app.app_context():
         db.create_all()
         db.session.commit()

# What you should add:

app = create_app()

# ONLY FOR PRE!!!

if __name__ == "__main__":
        app.run(debug=True, port=3000)

It might be that’s something else is missing in what I supplied, but for sure you need to execute the function in order to, prepare yourself, to function

Kind regards

UPDATED:

What about having everything in main?

from flask import Flask, g

def create_app():
    app = Flask(__name__)
    # app.config.from_file("config.json", load=json.load)
    # app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(minutes=10)
    return app

app = create_app()

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

if __name__ == "__main__":
    app.run(debug=True, port=3000)

I’ll recommend following application factories with blueprints here

Answered By: vgenovpy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.