Flask RuntimeError: Working outside of application context

Continuing the discussion from Flask Database Setup Lesson: Runtime Error:

From what I can tell, this was never resolved in a satisfactory manner. It took me a long time to figure out, hope this helps. I reset my environment, re-installed libraries, tried everything, nothing worked - until I added the following into my app.py:

# import all your libraries... # Create Flask application instance, configuration, database app = Flask(__name__) app.config["SECRET_KEY"] = "my_secret_key" app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///emails_passwords.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # SQLAlchemy is an ORM # define your models, forms.... with app.app_context(): db.create_all() # don't forget to indent this line, or else you will get an error # Run development server locally if __name__ == '__main__': app.run(debug=True)

What this does is create a new folder called instance in which your database now lives (also different from the Codecademy video - in the vid, the file simply appears on the same level as the app). Since I named mine emails_passwords.db, this is what it will be called. See screenshot for reference:

This fixed it for me except my myDB.db file was in a folder called “var”. I resorted to ChatGPT to troubleshoot my code and it gave me the same answer. I guess maybe Python has been updated which means the commands have changed?

1 Like

Not sure why but things have definitely changed. Glad ChatGPT gave you the same answer. I experimented and scrolled forums endlessly until I got there, still not sure if it’s the best solution but it works for now.

1 Like