Pythonic way to correctly separate Model from application using SQLAlchemy

后端 未结 2 957
无人及你
无人及你 2021-01-30 05:05

I\'m having a hard time to make my application run. Flask-SQLAlchemy extension creates an empty database whenever I try to separate module in packages. To better explain what I\

2条回答
  •  盖世英雄少女心
    2021-01-30 05:15

    Your problem is this line:

    db = SQLAlchemy(app)
    

    it should be this:

    db.init_app(app)
    

    By running SQLAlchemy app again, you're reassigning db to the newly created db obj.

    Please try NOT to move away from the application factory setup. It removes import time side effects and is a GOOD thing. In fact, you may want to import db inside your factory because importing a model that subclasses the Base (db.model in this case) has side effects of its own (tho less of an issue).

    Initializing your app in a __init__.py means that when you importing anything from your package for use, you're going to end up bootstrapping your app, even if you don't need it.

提交回复
热议问题