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
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:
and was able to get all users from my DB:
[User('alcatraz', 'email@example.com', 'c815f485bc056281.jpg'), User('peperabane', 'firstname.lastname@example.org', 'default.jpg'), User('papa', 'email@example.com', '97a063dcd433adb7.jpg'), User('itpro', 'firstname.lastname@example.org', 'default.jpg'), User('toby', 'email@example.com', 'default.jpg'), User('alan', 'firstname.lastname@example.org', 'default.jpg'), User('paco', 'email@example.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.