Forums

ImportError: cannot import name '_app_ctx_stack' from 'flask'

Hello,

I'm seeing the following error after installing Flask-Security and changing a data-type in my databse from varchar(255) to db.Text in db.Model and longtext in the sql table:

2024-11-04 22:44:12,901: Error running WSGI application
2024-11-04 22:44:12,901: ImportError: cannot import name '_app_ctx_stack' from 'flask' (/home/kpuln/.local/lib/python3.10/site-packages/flask/__init__.py)
2024-11-04 22:44:12,902:   File "/var/www/kpuln_pythonanywhere_com_wsgi.py", line 16, in <module>
2024-11-04 22:44:12,902:     from flask_app import app as application  # noqa
2024-11-04 22:44:12,902: 
2024-11-04 22:44:12,902:   File "/home/kpuln/mysite/flask_app.py", line 12, in <module>
2024-11-04 22:44:12,902:     from flask_sqlalchemy import SQLAlchemy
2024-11-04 22:44:12,902: 
2024-11-04 22:44:12,902:   File "/usr/local/lib/python3.10/site-packages/flask_sqlalchemy/__init__.py", line 14, in <module>
2024-11-04 22:44:12,902:     from flask import _app_ctx_stack, abort, current_app, request**

A Google search revealed that the issue could be with Flask, Werkzeug and Flask-SQLAlchemy.

So I rolled Flask-SQLAlchemy back to 2.5.1 from 3.1.1

I also rolled back Werkzeug from 3.1.1 to 2.1.2, which was upgraded to 3.1.1 after the Flask-Security module was installed.

and I rolled back Flask from 3.0.3 to 2.1.2, which was also upgraded to 3.0.3 after the Flask-Security module was installed.

Any suggestions on how I can resolve this issue AND work with Flask-Security..?

Thanks,

kpuln

Yes, this error often happens when there’s a version incompatibility between Flask and Flask-SQLAlchemy. The _app_ctx_stack import from flask was removed in more recent versions of Flask (from version 2.3 onward), so older versions of flask_sqlalchemy that rely on _app_ctx_stack will raise an ImportError.

Either: - Make sure you're using the latest version of flask_sqlalchemy, which is compatible with Flask 2.3 and later - If updating flask_sqlalchemy is not feasible, you can downgrade Flask to a version prior to 2.3

To resolve the errors, I found that the following combination works:

pip install --upgrade Flask==2.3.2

pip install --upgrade Flask-SQLAlchemy==3.0.3

But, now I'm running into the following error message, which is perplexing:

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?

Here is my init file:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_session import Session

session = Session()

db = SQLAlchemy()


def create_app():
    app = Flask(__name__, static_folder='static')

    from .flask_app import app as flask_app_blueprint
    app.register_blueprint(flask_app_blueprint)

    SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
        username="****",
        password="****",
        hostname="****.mysql.pythonanywhere-services.com",
        databasename="*****",
    )
    app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
    app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    app.config['SECRET_KEY'] = "*****"

    app.config["SESSION_PERMANENT"] = False
    app.config["SESSION_TYPE"] = "filesystem"

    session.init_app(app)

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'main.login'
    login_manager.init_app(app)

    from model import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    return app

if __name__ == "__main__":
    create_app()

Everything was running well until I installed the Flask-Security module, which I have sense uninstalled.

Do you have any additional suggestions as to how I can resolve this issue..?

Thanks again

Is the line app = Flask(__name__, static_folder='static') aligned properly in your code? Because it doesn't look like it is in your post

In the code, yes it is... It may have gotten misaligned here when I copy and pasted it, as I tried to put 4 spaces in front of each line.

Could you show us how you defined the application object in the WSGI file? It should call create_app from your init file.

Here it is:

# import flask app but need to call it "application" for WSGI to work
from flask_app import app as application  # noqa

from mysite import create_app
application = create_app()

Ok... I was able to resolve the problem...

Apparently, I was declaring the following twice:

db = SQLAlchemy()

I forgot that earlier, to resolve another issue, I had to define "db" in another file and import it. So in this case, I had to add the following line to my init.py file and remove the "db = SQLAchemy()" line and it resolved the issue:

from db_file import db

So far so good...

Thanks again...

kpuln

Glad you got it working