When scattering Flask Models, RuntimeError: 'application not registered on db' was raised

后端 未结 2 743
执念已碎
执念已碎 2020-11-28 04:12

I am re-factoring my Flask application by scattering the models, blueprints but I am having a runtime error.

def create_app():
    app = flask.Flask(\"app\"         


        
2条回答
  •  甜味超标
    2020-11-28 04:33

    Mark's answer was great and it helped me a lot. However, another way to approach this is to run the code that relies on the app context in a function decorated with @app.before_first_request. See http://flask.pocoo.org/docs/0.10/appcontext/ for more information. That's in fact how I ended up doing it, largely because I wanted to be able to call the initialization code outside of flask as well, which I handle this way.

    In my case I want to be able to test SQLAlchemy models as plain SQLAlchemy models without Flask-SQLAlchemy, though the db in the code below is simply a (Flask) SQLAlchemy db.

    @app.before_first_request
    def recreate_test_databases(engine = None, session = None):
      if engine == None:
        engine = db.engine
      if session == None:
        session = db.session
    
      Base.metadata.drop_all(bind=engine)
      Base.metadata.create_all(bind=engine)
      # Additional setup code
    

提交回复
热议问题