2

Before claiming this is a duplicate, I have searched through countless errors and I have not been able to find a solution that works for me.

I have a flask web application that I am sql alchemy to facilitate the connection with my google sql database. I need to create the tables corresponding to my application upon creating my application using the db.create_all() function. However, every-time I do so I get the error: "'No application found. Either work inside a view function or push' RuntimeError: No application found. Either work inside a view function or push an application context"

Here is the code that I currently have. I would appreciate any help you would be able to offer:

db = SQLAlchemy()

def create_app():
  app = Flask(__name__)

  app.config.from_object(config)

  db.init_app(app)

  login_manager = LoginManager()
  login_manager.login_view = 'auth.login'
  login_manager.init_app(app)

  from .models import User

  @login_manager.user_loader
  def load_user(user_id):
    return User.query.get(int(user_id))

  from .auth import auth as auth_blueprint
  app.register_blueprint(auth_blueprint)

  from .main import main as main_blueprint
  app.register_blueprint(main_blueprint)

  with app.app_context():
      db.create_all()

  return app
jewelltaylor9430
  • 109
  • 1
  • 15

1 Answers1

3

Try replacing

with app.app_context():
    db.create_all()

with

app.app_context().push()
db.create_all()

For more info refer to the flask_sqlalchemy contexts docs.

By the way, you're using a newly created SQLAlchemy class that doesn't know which structure has to apply to the new DB. You should use the db object created with your models from .models import User, db.

mrrb
  • 31
  • 1