12

Checking Flask and Flask-SQLAlchemy doc i have a confusion, if i have:

models.py:

from flask_sqlalchemy import SQLAlchemy
#:Use or not
db = SQLAlchemy()

class User(db.Model):
 __tablename__ = "USERS"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), nullable=False)
    password = db.Column(db.String(255), nullable=False)

config.py:

import os

class Config(object):
    DEBUG = True
    SECRET_KEY = os.urandom(12)
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_DATABASE_URI = "mysql://root:@localhost/example"

app.py:

from config import Config
from models import db
from models import User

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)

if __name__ == "__main__":
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.run()

is necessary use:

db = SQLAlchemy(app) after app.config.from_object(Config) or db.init_app(app) is the same?

Because i founded some examples of flask with only db = SQLAlchemy() in models.py and have db.init_app(app) before app.run()

And so founded examples with db = SQLAlchemy(app) override in app.py with no db.init_app(app)

I printed both values and get:

with only db in models:

<SQLAlchemy engine=None>
the problem is:
The app create the tables in my database
But engine=None

with db = SQLAlchemy(app) override

<SQLAlchemy engine=mysql://root:***@localhost/hsl_db?charset=utf8>

the problem is:
The app dont create the tables in my database

What is the correct way to assign the database of SQLAlchemy to Flask app?

Dev 200
  • 246
  • 1
  • 6
  • 12

3 Answers3

14

From: https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/

There are two usage modes which work very similarly. One is binding the instance to a very specific Flask application:

app = Flask(__name__)
db = SQLAlchemy(app)

The second possibility is to create the object once and configure the application later to support it:

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

The difference between the two is that in the first case methods like create_all() and drop_all() will work all the time but in the second case a flask.Flask.app_context() has to exist.

Rick
  • 2,080
  • 14
  • 27
7

There is no correct way as it all depends on how you want to instantiate your db using SQLAlchemy and app using Flask. But I'll go over how I use the app.

def create_app():
    app = Flask(__name__, static_folder='static', instance_relative_config=True)
    app.config.from_pyfile('app_config.py')
    return app

app = create_app()
db = SQLAlchemy(app)
Jessi
  • 1,378
  • 6
  • 17
  • 37
2

The Flask documentation recommends:

db.init_app(app)

Flask Factories & Extensions

jbrcodes
  • 21
  • 2