Recently when I was doing a project in python, I tried to install the requirements.txt of the project, and it gave me an unexpected error, ‘ImportError: cannot import name ‘escape’ from ‘jinja2’. Below is a snippet of the error shown:
ImportError: cannot import name 'escape' from 'jinja2'
Even after trying to install the package directly through pip install, it said the requirement is already satisfied.
pip install jinja2
I would like to share the steps that helped me to fix the error, ‘ImportError: cannot import name ‘escape’ from ‘jinja2”.
Why ImportError cannot import name ‘escape’ from ‘jinja2 error is seen?
The error, ImportError: cannot import name ‘escape’ from ‘jinja2 is seen because Jinja is a dependency of Flask, and Flask V1.X.X is using the escape module through Jinja. However, recently, In the newer version of Flask there, the escape modules are no longer supported. You can read more about it here.

A simple solution to fix this is to update to the newer version of Flask that is Flask V2.X.X, in the requirements.txt of your project..
A detailed solution to fix the ImportError: cannot import name ‘escape’ from ‘jinja2 error is provided below:
How to Fix ImportError cannot import name ‘escape’ from ‘jinja2 error?
To fix the issue ImportError: cannot import name ‘escape’ from ‘jinja2’, simply update to the newer version of Flask V2.X.X in your requirements.txt where Flask no longer uses the escape
module from Jinja.
Flask==2.1.0
Also, do note that the team has stopped the support of Flask V1.X.X . If you want to continue to use this older version, this Github issue may help, and here is its link.
If this does not fix the ImportError: cannot import name ‘escape’ from ‘jinja2’ error it is possible that the error is from the code you wrote, so you can fix it by importing it from MarkupSafe, as it is given in the Jinja release notes.
So, you should use
from markupsafe import escape
instead of
from jinja2 import escape
Also if this line of code is present in your project, consider changing it to the code mentioned below.
text = jinja2.utils.escape(text)
to text = escape(text)
Conclusion
To fix the ImportError: cannot import name ‘escape’ from ‘jinja2’ error; A simple solution to fix this is to update to the newer version of Flask that is Flask V2.X.X, in the requirements.txt of the project. If you are still having the same error, it is possible your error is from the code you wrote, so you can fix it by importing it from MarkupSafe, as suggested in the Jinja release notes and in the article above.