Skip to content
Advertisement

Flask-SQLAlchemy db.create_all() raises RuntimeError working outside of application context

I recently updated Flask-SQLAlchemy, and now db.create_all is raising RuntimeError: working outside of application context. How do I call create_all?

JavaScript

This raises the following error:

JavaScript

Advertisement

Answer

As of Flask-SQLAlchemy 3.0, all access to db.engine (and db.session) requires an active Flask application context. db.create_all uses db.engine, so it requires an app context.

JavaScript

When Flask handles requests or runs CLI commands, a context is automatically pushed. You only need to push one manually outside of those situations, such as while setting up the app.


Instead of calling create_all in your code, you can also call it manually in the shell. Use flask shell to start a Python shell that already has an app context and the db object imported.

JavaScript

Or push a context manually if using a plain python shell.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement