Skip to content

Reload the DB URL/bind config when calling db.create_all #1172

@greyli

Description

@greyli

After 3.0, the engines is created in init_app, so there is no way to update the configuration after instantiating the extension object. However, we do need to update the config in some use cases. For example, in a simple application without using the app factory:

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'secret string')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv(
'DATABASE_URL', 'sqlite:////' + os.path.join(app.root_path, 'data.db')
)
db = SQLAlchemy(app)

In the test, you will want to use a different database URL, so you reset the config SQLALCHEMY_DATABASE_URI:

from app import app, db

class NotebookTestCase(unittest.TestCase):

    def setUp(self):
        self.context = app.test_request_context()
        self.context.push()
        self.client = app.test_client()
        app.config.update(
            TESTING=True,
            WTF_CSRF_ENABLED=False,
            SQLALCHEMY_DATABASE_URI='sqlite:///:memory:'  # <--
        )
        db.create_all()

It works in 2.x, but not 3.x.

I think we need to reload the config (SQLALCHEMY_DATABASE_URI and SQLALCHEMY_BINDS) before calling create_all, but it seems there is no way to update the engine URL after creating it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions