# Fix "ImportError: cannot import name 'escape' from 'jinja2'" in a Flask 1.x App

Yes. An agent traces the failed Flask 1.x import to its unpinned packages, then pins a set that imports or moves the app to current Flask, and runs the tests.

[Run this on Rush](https://cloud.getrush.ai/run/fix-jinja2-escape-import-error/jinja2/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Jinja2 3.1 dropped `escape` and `Markup`, two names it had only been passing along from MarkupSafe. Flask 1.x imports both at module scope: line 14 of `flask/__init__.py` in Flask 1.1.1 reads `from jinja2 import escape`. So the failure is not in your templates or your views. `import flask` itself stops, and the traceback points into site-packages. Arrotech/Flask-Payment-Gateway, a Braintree checkout example, shows how an app gets there. Its `requirements.txt` pins `Flask==1.1.1` exactly and then lists `Jinja2>=2.4`, `itsdangerous>=0.21`, `Werkzeug>=0.7` and `MarkupSafe>=0.23` with no upper bound. The one pinned package is the one that depends on old versions of the other four.

The agent reproduces the error in a clean virtual environment: `pip install -r requirements.txt`, then `python -c "import flask"`. It also explains why the project's own container may never have shown it. The `Dockerfile` starts `FROM python:3.5.3`, and on that interpreter pip only considers releases that still declare support for Python 3.5, which keeps Jinja2, itsdangerous and Werkzeug at versions Flask 1.1.1 was written against. The `Procfile` is a different story. It runs `gunicorn app:app`, the repository has no `runtime.txt`, and the README offers a Heroku deploy button, so the platform picks the Python version and pip resolves every open range to today's release.

The title's error is the first of three, and the agent walks all of them, keeping each traceback. Capping Jinja2 below 3.1 gets past line 14, and the import then stops in `flask/json/__init__.py` with `cannot import name 'json' from 'itsdangerous'`. Capping itsdangerous below 2.1 moves it to `flask/app.py`, which fails on `from werkzeug.wrappers import BaseResponse`. Capping Werkzeug below 2.1 is the last step. On Python 3.11, Jinja2 3.0.3 with itsdangerous 2.0.1 and Werkzeug 2.0.3 lets Flask 1.1.1 import. Anyone who fixes only the message they searched for meets the next one a minute later, which is why the agent reports the whole chain in order.

Then it offers two routes and says what each costs. The small one adds the three upper bounds to `requirements.txt` and leaves Flask alone. The larger one raises Flask to a current release: `app.py` imports `Flask`, `redirect`, `url_for`, `render_template`, `request` and `flash`, all of which Flask 3 still exports, so the application code may need no change at all. Either way the agent runs `test_app.py`, a `unittest` suite that patches `ClientTokenGateway.generate` and `TransactionGateway.find` with `mock`, after filling the five variables named in `example.env` with placeholder values. It reports the result per route and does not present a route as working unless the suite ran on it.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Starting this Flask app fails with \"ImportError: cannot import name 'escape' from 'jinja2'\". Reproduce it first: create a clean virtual environment on the Python version the deployment uses (read the Dockerfile, runtime.txt, Procfile and CI config to find it; if they disagree or say nothing, use a current Python and say so), install the requirements exactly as written, run python -c \"import flask\" and save the full traceback. Read the requirements file and list which packages are pinned exactly and which are open ranges. Flask 1.x needs older Jinja2, itsdangerous, Werkzeug and MarkupSafe, so after you get past the first error, keep going: record every further import error in the order it appears, with the package and version that caused it, until import flask succeeds. Then prepare two options on separate commits. Option one keeps the pinned Flask and adds the smallest set of upper bounds or exact pins that makes the app import. Option two upgrades Flask to a current release, fixes any imports or APIs the app uses that changed, and pins the versions you tested. For each option run the test suite and start the app far enough to serve one request, using placeholder values for any environment variables the app needs. Do not use real payment credentials. Open a pull request with option one as the base commit and option two on top, and in the description list every error in order, the resolved versions for each option, the test output for each, and anything you could not verify.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request with two commits. The first touches only `requirements.txt`: upper bounds, or exact pins, for Jinja2, itsdangerous and Werkzeug, and for MarkupSafe if the versions it tested need one. The second raises Flask and replaces the open ranges with the versions the tests ran against. The description lists the three import errors in the order pip's choices produce them, each with the file inside Flask that raised it, and then the `pip freeze` output for each commit.

A reviewer decides which commit to keep. The first is the low-risk change for an app that only needs to start again. The second is the one that stops the problem from returning, since Flask 1.x is no longer released and every new major version of a package it depends on is another chance of the same failure. Before merging either, check the Python version the description says it used against the one your host runs, because the set of versions pip picks depends on it. If the test suite could not run, the description says which step failed, and the commits are still there to try locally.

## Run it on every Monday morning

This error arrives without a commit. A package publishes a new major version, the next clean install picks it up, and the app that worked on Friday no longer imports. A weekly clean install catches that before a deploy does. In the Project that holds the repository, add an automation with a `schedule` trigger, a weekly `cron` and your `timezone`, and a prompt that installs the requirements into a fresh environment, imports the app, runs the tests and fixes what fails, modelled on the request above.

Most weeks nothing has moved and the run reports a clean install and opens no pull request. If your deploy pipeline already tells you when a build fails, start the run from there instead: give the automation a `webhook` trigger and have your pipeline's failure hook call its URL with `Authorization: Bearer` and the trigger's secret. The build log you post, up to 64 KB, is added after the prompt as event text.

## Why run it on Rush?

The bug lives in the gap between two environments: the one where the app last worked and the one a fresh install produces today. A laptop usually holds the first, with packages installed long ago, and that is why the app runs for you and fails on the host. The agent starts from an empty sandbox, so it sees what a new deploy sees, and it can build several environments side by side to compare a pinned set against an upgraded Flask. Every install log and traceback is kept in the session's transcript, so the order of the three errors in the pull request can be checked against what pip printed.

It is also a job that is easy to do halfway. Pinning Jinja2 alone turns one import error into another, and a pin chosen on one Python version may not resolve on the next. The run does the tedious part, one cap at a time until the import succeeds, and hands back a set of versions it installed and tested together, with the commands that prove it.

## Frequently asked questions

### Can I just pin Jinja2 to fix this?

It removes this message and usually shows you the next one. With Flask 1.1.1 and open ranges, capping Jinja2 below 3.1 leads to `cannot import name 'json' from 'itsdangerous'`, and capping that leads to a `BaseResponse` import error from Werkzeug. Cap all three, or upgrade Flask.

### Why does the same requirements file work in my Docker image?

Probably because the image has an old Python. pip skips releases that no longer support the interpreter it runs on, so an image built from a Python 3.5 base still receives versions from the Flask 1.x era. The same file on a current Python resolves the open ranges to current releases.

### My own code has `from jinja2 import escape`. Is that the same fix?

No, and it is simpler. Import the name from where it has always lived: `from markupsafe import escape`, and the same for `Markup`. The agent searches the application for both imports and changes them in the same pull request.

### Does upgrading Flask from 1.x mean rewriting the app?

Often not. A small app that uses routes, templates, `request`, `redirect`, `url_for` and `flash` relies on APIs that are still there. Extensions are the usual obstacle, since each has its own minimum Flask version. The agent lists every Flask extension in the requirements and reports which ones had to move.

## More Jinja2 jobs

- [Fix "ImportError: cannot import name 'contextfilter' from 'jinja2'"](https://getrush.ai/run/fix-jinja2-contextfilter-import-error/jinja2/)

## More jobs like this: Fix a bug from an alert

- [Fix Jira Bug Tickets With Pull Requests in an ASP.NET Core App](https://getrush.ai/run/fix-jira-bugs/aspnet-core/)
- [Fix Jira Bug Tickets With Pull Requests in a Django App](https://getrush.ai/run/fix-jira-bugs/django/)
- [Fix Jira Bug Tickets With Pull Requests in a Laravel App](https://getrush.ai/run/fix-jira-bugs/laravel/)
- [Fix Jira Bug Tickets With Pull Requests in a Next.js App](https://getrush.ai/run/fix-jira-bugs/nextjs/)
- [Fix Jira Bug Tickets With Pull Requests in a Rails App](https://getrush.ai/run/fix-jira-bugs/rails/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
