I am trying to write a flask application with a database, but the database already exists. I don't want to have to define all of my tables again in Python (e.g. in models.py) code just to interact with the database, since this would be doing the same thing twice (sort of). But I can't seem to find a clear example of how to do this. I can see several questions asking the same thing but the response is not clear.
In my __init__.py file, I have
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.automap import automap_base
...
db = SQLAlchemy()
Base = automap_base()
def create_app():
app = Flask(__name__)
...
db.init_app(app)
...
Base.prepare(autoload_with=db.engine, schema="my_schema")
And then in my models.py file, I have
from . import db, Base
MyTable = Base.classes.my_table
I simply want to import MyTable into the views.py and run queries from it, as you would with standard Flask-SQLAlchemy. But on trying to start the app, I receive:
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
I do not want to solve this error - I want to access my database correctly, because I am sure that I am doing this wrong. As I have never used SQLAlchemy properly, only basic Flask-SQLAlchemy, I am pretty lost. Is there an obvious/simple/clear/recommended way to just connect and use an existing database in my flask app?