You are reading this because you have come across this error”importerror: cannot import name ‘escape’ from ‘jinja2’” when you were running your project. In this post, we have compiled the best solutions to the importerror: cannot import name ‘escape’ from ‘jinja2’ error in order to continue with your project smoothly.
The cause of this importerror: cannot import name ‘escape’ from ‘jinja2’ error is; in the updates of Flask, that is from Flask 2.X.X upwards, they have dropped the support of the escape module from Jinja2.
Also, the Flask team do not the Flask 1.x.x again, so if you are still using that version, it means you are using an outdated version that isn’t maintained by the team.
There are two ways you can solve this The cause of this importerror: cannot import name ‘escape’ from ‘jinja2’ error; one is by upgrading Flask and the other is by changing all escape modules from Jinja2 to Markupsafe.
Method 1: Upgrading Flask
The method has worked for many users. Upgrade Flask to any 2.X.X. version. You can use the code below to install the latest version of Flask.
pip install flask
The above command is for the latest version of Flask. If you have your preferred version 2.x.x., then you can use the code below.
pip install flask==2.x.x
If the above didn’t work, continue with the following.
Method 2: Using MarkupSafe
Since Flask 1.x.x doesn’t support the Jinja2 escape module, then you need to import the escape module from MarkupSafe. To import the escape module from MarkupSafe, use the command below.
from markupsafe import escape
instead of
from jinja2 import escape
Version Combinations that work
These are some of the version combinations that has worked for most people; using the latest update of flask, jinja2 and markupsafe.
You can also use the flask 1.x.x version with with jinja2 for it to work