1
votes

I have created a small Flask application which stores its data in an sqlite database that I access via flask-sqlalchemy.

However, when I run it, I get the following error: RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

I have debugged my application and now know that this error stems from these two functions: ```def user_exists(email): if User.query.filter_by(email = email).count() == 0: return False else: return True

def get_user(email): user = User.query.filter_by(email = email).first() return user```

Now I am wondering: Is it impossible to access the database via flask-sqlalchemy outside of view functions?

For further context, I added the files in which I configure my flask app:

presentio.py

from app import create_app

app = create_app(os.getenv("FLASK_CONFIG", "default"))

app/init.py

from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from config import config

mail = Mail()
db = SQLAlchemy()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    db.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix = "/auth")

    from .text import text as text_blueprint
    app.register_blueprint(text_blueprint, url_prefix = "/text")

    return app

1

1 Answers

0
votes

You need to give the flask app a context after you create it. This is done automatically in view functions, but outside those, you need to do this after you create the app:

app.app_context().push()

See the docs: https://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/