2

I am trying to connect to an existing database and I am unsure where to put db.Model.metadata.reflect(db.engine) as shown in the following question.

My flask app that is structured like:

enter image description here

I am not sure where to add db.Model.metadata.reflect(db.engine).

In intel\__init__.py I am using a function to create app:

def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    register_extensions(app)
    register_blueprints(app)
    return app

And in my register_extensions function:

def register_extensions(app):
    db.init_app(app)
    db.Model.metadata.reflect(db.engine)
    return None

in my model\sam.py

from intel.database import db


class Sam(db.Model):
    __table__ = db.Model.metadata.tables['sam_monthly_extract']

Now, when I do that I get an error:

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from intel import create_app
  File "C:\Users\spitf\G2XChange\intel_app\intel\__init__.py", line 6, in <module>
    from intel.views.sam_view import sam_blueprint
  File "C:\Users\spitf\G2XChange\intel_app\intel\views\sam_view.py", line 3, in <module>
    from intel.models.sam import Sam
  File "C:\Users\spitf\G2XChange\intel_app\intel\models\sam.py", line 4, in <module>
    class Sam(db.Model):
  File "C:\Users\spitf\G2XChange\intel_app\intel\models\sam.py", line 5, in Sam
    __table__ = db.Model.metadata.tables['sam_monthly_extract']
KeyError: 'sam_monthly_extract'

What am I doing wrong?

Edit:

run.py

from intel import create_app

app = create_app()
app.run(debug=True)
spitfiredd
  • 2,897
  • 5
  • 32
  • 75

1 Answers1

1

I came across your question in my search for an answer to the same exact problem and since it helped me actually get there, I had to make sure to come back and provide you with what helped solve my issue.

What I think was happening was that the __init__.py that contained the application factory was imported from my run.py and so was the import of the models.py which was at the bottom of the __init__ file, which imported before I could run the function to create the app and not having any context from which to pull that table from. That's at least the best I can explain it currently.

What solved it for me was to move the models import into the application factory, explicitly under the app context, right after db.init_app() like so:

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)

    with app.app_context():
        db.Model.metadata.reflect(db.engine)
        from app import models

Not sure if that is the best way to do it, but it's been working for me ever since.

zmrl
  • 11
  • 1