Flask - Resolve "The current Flask app is not registered with this 'SQLAlchemy' instance"
by
Jeremy Canfield |
Updated: August 05 2023
| Flask articles
Let's say something like this is being returned.
RuntimeError: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
And let's say this occurs when attempting to append records to a table using Flask. In this example, perhaps your view has something like this.
from flask import Blueprint, render_template
from sqlalchemy import func, exc
from . import db
from .models import users
views = Blueprint('views', __name__)
@views.route('/test')
def test():
firstname = "john"
lastname = "doe"
try:
db.session.add(data)
except Exception as exception:
print("got the following exception when attempting db.session.add(data))
print("data = " + str(data))
print(exception)
finally:
db.session.close()
try:
db.session.commit()
except exc.SQLAlchemyError as sqlalchemyerror:
print("got the following SQLAlchemyError: " + str(sqlalchemyerror))
except Exception as exception:
print("got the following Exception: " + str(exception))
finally:
db.session.close()
return render_template('test.html')
Notice in this example that "firstname" and "lastname" are being appended to the users table. In this scenario, your model should have something like this.
from . import db
class users(db.Model):
id = db.Column(db.Integer, nullable=False, unique=True, primary_key=True)
firstname = db.Column(db.String(50), nullable=False, unique=True)
lastname = db.Column(db.String(50), nullable=False, unique=False)
Notice the error says "Did you forget to call init_app". Ensure __init__.py includes init_app.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def app_obj():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db.init_app(app)
# this is needed in order for database session calls (e.g. db.session.commit)
with app.app_context():
try:
db.create_all()
except Exception as exception:
print("got the following exception when attempting db.create_all() in __init__.py: " + str(exception))
finally:
print("db.create_all() in __init__.py was successfull - no exceptions were raised")
from .models import users
return app
If issues persist, add the following to __init__.py.
app.config["SQLALCHEMY_ECHO"] = True
app.config["SQLALCHEMY_RECORD_QUERIES"] = True
Did you find this article helpful?
If so, consider buying me a coffee over at
Comments
November 01 2023 by SAM
Hi
Thank you fr your comments
I tried your code, but because you used db.session.close() in the view file, the data not saved in the db and when you remove it, the mentioned issue persist! can you help me?