Skip to content Skip to sidebar Skip to footer

SQLAchemy 'No Application Found. Either Work Inside A View Function Or Push'

Ello ello, I found similar questions on the bug i'm facing, and tried the solutions offered but it didn't work for me. I'm trying to separate out my models in a different director

Solution 1:

Flask-SQLAlchemy needs an active application context.

Try:

with app.app_context():
    print(Todo.query.count())

From the flask documentation:

Purpose of the Context

The Flask application object has attributes, such as config, that are useful to access within views and CLI commands. However, importing the app instance within the modules in your project is prone to circular import issues. When using the app factory pattern or writing reusable blueprints or extensions there won’t be an app instance to import at all.

Flask solves this issue with the application context. Rather than referring to an app directly, you use the the current_app proxy, which points to the application handling the current activity.

Flask automatically pushes an application context when handling a request. View functions, error handlers, and other functions that run during a request will have access to current_app.


Solution 2:

It is ok to have db initialised in app.py

from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from routes import test, root, user

app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:pass123@localhost/db'
app.config['SECRET_KEY'] = 'thiskeyissecret'
db = SQLAlchemy(app)

api.add_resource(root.HelloWorld, '/')
api.add_resource(test.Test, '/test')
api.add_resource(user.User, '/user')

if __name__ == '__main__':
    app.run(debug=True)

Then in your todo.py

from app import db


class Todo(db.Model):
    __tablename__ = 'Todos'
    id = db.Column('id', db.Integer, primary_key=True)
    data = db.Column('data', db.Unicode)

    def __init__(self, id, data):
        self.id = id
        self.data = data

    def __repr__(self):
        return '<Todo %>' % self.id

Solution 3:

I get a same err that err reason for just can operation db in viewfunc

def __init__(self, id, data):
        self.id = id
        self.data = data

try move that code operation to your viewfunc


Solution 4:

In a nutshell, do something like this:

from yourapp import create_app
app = create_app()
app.app_context().push()

Post a Comment for "SQLAchemy 'No Application Found. Either Work Inside A View Function Or Push'"