Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

ImportError for _app_ctx_stack after upgrading to Flask 3

Your error

ImportError: cannot import name '_app_ctx_stack' from 'flask' (/app/.venv/lib/python3.12/site-packages/flask/__init__.py)2 more lines it can show

Fix it fast

Most common cause, 1 of 2

Flask-SQLAlchemy 2.x is still installed next to Flask 3

Upgrade the extension to the 3.1 line and pin it.

Fix
python -m pip install -U "flask-sqlalchemy>=3.1"

# in your start-up code
with app.app_context():
    db.create_all()
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

ImportError: cannot import name '_app_ctx_stack' from 'flask' means some code still uses an object that Flask deprecated in 2.2 and deleted in 3.0. Most often it is Flask-SQLAlchemy 2.5.1, which pip leaves in place when Flask moves to 3.x. Upgrade to Flask-SQLAlchemy 3.1, or rewrite your own code to use g and current_app. Applies to Flask 3.0 to 3.1.3.

  • Applies to Flask 3.1.3, Flask-SQLAlchemy 3.1.1, Python 3.12
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Read the File line just above the ImportError in the traceback. When that line sits in site-packages/flask_sqlalchemy, go to cause 1; any other module, yours or a third party's, means cause 2. The two commands below show the installed versions and every remaining import.

Run this first
python -m pip list | grep -i "^flask"
grep -rn "_app_ctx_stack\|_request_ctx_stack" --include=*.py .

Then find the line you see in this list and open its fix:

  1. 1Flask-SQLAlchemy 2.x is still installed next to Flask 3The traceback points into site-packages/flask_sqlalchemy/__init__.py, and pip list shows Flask-SQLAlchemy 2.5.1
  2. 2Your own code or another old extension uses the context stacksThe grep finds _app_ctx_stack.top or _request_ctx_stack.top in your project, or the traceback ends in a different package

What does the error look like?

  • ImportError: cannot import name '_app_ctx_stack' from 'flask' (/app/.venv/lib/python3.12/site-packages/flask/__init__.py)
  • from flask import _app_ctx_stack, abort, current_app, request
  • ImportError: cannot import name '_request_ctx_stack' from 'flask'

Cause 1 of 2

Flask-SQLAlchemy 2.x is still installed next to Flask 3

You seeThe traceback points into site-packages/flask_sqlalchemy/__init__.py, and pip list shows Flask-SQLAlchemy 2.5.1

Check

This ImportError comes from Flask-SQLAlchemy 2.5.1, whose first lines import _app_ctx_stack from flask. That release declares only Flask>=0.10 with no upper limit, so upgrading Flask to 3.x does not pull a newer extension with it. Flask's 2.3 changelog removed the push and pop methods of the stack, and 3.0 removed the remaining deprecated code.

Check
python -m pip show flask-sqlalchemy | grep -i "^version"

Fix

Upgrade the extension to the 3.1 line and pin it. Version 3.0 changed behaviour, so wrap start-up calls such as create_all in an application context, because the session and engine now need one.

Fix
python -m pip install -U "flask-sqlalchemy>=3.1"

# in your start-up code
with app.app_context():
    db.create_all()

Verify

The import works, and the app starts without the error. If it now says Working outside of application context, add the app_context block shown above.

Verify
python -c "import flask_sqlalchemy, importlib.metadata as m; print(m.version('flask-sqlalchemy'))"

Confirmed by flask-sqlalchemy.readthedocs.io

Did this fix it?

Cause 2 of 2

Your own code or another old extension uses the context stacks

You seeThe grep finds _app_ctx_stack.top or _request_ctx_stack.top in your project, or the traceback ends in a different package

Check

The same error appears for any module that still reads the stacks Flask used before 2.2. That release moved app and request contexts to Python context variables and told extension authors to stop using _app_ctx_stack.top and _request_ctx_stack.top. It suggested storing data on g with a unique prefix, and Flask 3.0 then deleted the stacks.

Check
grep -rln "_ctx_stack" --include=*.py "$(python -c 'import flask, os; print(os.path.dirname(os.path.dirname(flask.__file__)))')"

Fix

In your code, replace the stack lookups with the public proxies: current_app for the app, request for the request, and g for per-context data. For a third-party package, upgrade it to a release that supports Flask 3, or replace it if it is no longer maintained.

Fix
# before (Flask 2.1 style)
from flask import _app_ctx_stack
_app_ctx_stack.top.report_cache = {}

# after
from flask import g, current_app
g._reports_cache = {}
debug = current_app.debug

Verify

The grep returns nothing for your project and the server starts cleanly under Flask 3.

Verify
flask --app app run

Confirmed by flask.palletsprojects.com

Did this fix it?

How do I stop it coming back?

  • Pin Flask and each Flask extension together in requirements, so a Flask major upgrade is a deliberate change reviewed with its extensions.
  • Run the test suite with -W error::DeprecationWarning before a Flask upgrade; Flask 2.2 and 2.3 flagged the stacks as deprecated before 3.0 deleted them.
  • Keep extension data on g with a prefix of your own instead of importing names that start with an underscore.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.