1

I have a running Flask app with the following structure:

myproject/
    myapp.py
    models.py

I can run the app locally, and I can access it in a debugger (Pycharm for the curious). I am unable to fire up the db instance in the python interpreter and I need to be able to access the working objects to debug.

Here is what I am doing in the interpreter.

import sys
sys.path.append('/path/to/myproject/')
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from models import db, User, Post
app = Flask('myapp')
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/mydb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

I can call on the classes User and Post. If I, however, try to use query to access the underlying db, say User.query.all(), I am given

RuntimeError: application not registered on db instance and no application bound to current context

What needs to be done to get the interpreter to be able to access the db that is found when running from myapp.py? I don't think that I need all of the statements that I am using, but am struggling to find the right sequence of magic words to make the interpreter behave like my IDE.

davidism
  • 121,510
  • 29
  • 395
  • 339
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51

1 Answers1

1

Based on the documentation for http://flask-sqlalchemy.pocoo.org/2.1/api/

In particular,

The difference between the two is that in the first case methods like create_all() and drop_all() will work all the time but in the second case a flask.Flask.app_context() has to exist.

Can you ensure that you are under an app context with

with app.app_context():
    ...

http://flask.pocoo.org/docs/0.11/api/#flask.Flask.app_context

DanGar
  • 3,018
  • 17
  • 17
  • I saw the context handler as well. But the idea that I need to run the entire session within a context handler seems quite wrong to me. Furthermore, experimentation with it demonstrates that `p = Post.query.first()` only returns a class, no data from the db, so the same lack of db connection appears to still be the issue....Thanks for the thought, however. – Shawn Mehan Aug 21 '16 at 05:37