I have been working on a personal Flask app using SQLAlchemy for learning purposes and to improve my coding skills. As usual, I put it away for some months and then have to ‘re-learn’ what I did. Don’t do this! 🙂 I kept getting a new (at least for me!) error “RuntimeError: working outside of application context”.

In order to access the sqlite DB I run the python terminal and perform some imports for example:

from <myApp> import db
from <myApp.models> import User, Reading

The above used to work for me many months ago. When I tried last week I got the below error when trying a User.query.all()

RuntimeError: working outside of application context

After brewing a good coffee from Nicaragua using my Moka pot I was able to figure this one out. I discovered contexts in SQLAlchemy. The way to run the imports in Python terminal changed…at least for me since I did not keep up to date on Flask stuff. Below is my solution:

from mbp import create_app
app = create_app()
app.app_context().push()
from mbp.models import User, Reading

After running the above I was able to run a query:

User.query.all()

and was able to get all users from my DB:

[User('alcatraz', 'alca@traz.com', 'c815f485bc056281.jpg'), User('peperabane', 'pepe@rabane.com', 'default.jpg'), User('papa', 'papa@mama.com', '97a063dcd433adb7.jpg'), User('itpro', 'hello@itprohelper.com', 'default.jpg'), User('toby', 'rgmilanes@gmail.com', 'default.jpg'), User('alan', 'brito@yahoo.com', 'default.jpg'), User('paco', 'paco@yahoo.com', 'default.jpg')]

Hope this helps someone. You can always contact me if you have questions or like to collaborate. Also, remember to check my T-Shirt and coffee mugs shop. I make my own designs.

UPDATE: You should also refer to the latest SQLAlchemy documentation as of this writing. The link I provided above is what worked for me using version 2.x.

Leave a comment

Your email address will not be published. Required fields are marked *