ImportError: cannot import name ‘escape’ or ‘markup’ from ‘jinja2’

According to Jinja project, escape and markup should be imported from MarkupSafe. These functions are removed from jinja version 3.1.0.

If you are using jinja version <3.1.0 or flask version <V2, then you will get ImportError: cannot import name ‘escape’ or ‘markup’ from ‘jinja2’.

Solution

The solution to this issue is to either downgrade jinja to match compatible version of Flask, or upgrade Flask to version 2+.

Open your requirements.txt file and add this to the end of file –

Flask==2.1.0

Or, you can use MarkupSafe package –

>>> from jinja2.utils import markupsafe 
>>> markupsafe.Markup()

Or, you can also upgrade all the libraries listed in requirements.txt file –

pip install --upgrade <requirements.txt>

Conclusion

Flask has a dependency on jinja and that’s why you are getting this error. A simple upgrade will be enough to resolve it.