[Solved] ImportError: cannot import name 'escape' from 'jinja2'

Python Faysal Shuvo

Problem: 

I am using Jinja2 as my templating language. The following are my requirements.txt: 

chart_studio==1.1.0
dash==2.1.0
dash_bootstrap_components==1.0.3
dash_core_components==2.0.0
dash_html_components==2.0.0
dash_renderer==1.9.1
dash_table==5.0.0
Flask==1.1.2
matplotlib==3.4.3
numpy==1.20.3
pandas==1.3.4
plotly==5.5.0
PyYAML==6.0
scikit_learn==1.0.2
scipy==1.7.1
seaborn==0.11.2
statsmodels==0.12.2
urllib3==1.26.7

When I try to run this code I get this error:  

ImportError: cannot import name 'escape' from 'jinja2'

To solve the problem I tried installing jinja2.

pip install jinja2

But I am still getting the error. To let you know, the requirement is satisfied and I am running my code on windows os.

In this article, I am going to write about how to solve this problem.


Solution:

This problem is happening because jinja has removed these functions in a recent version. You can see all the upgrades from here.

So to solve your problem you have two options: 

1. This error is coming from your dependency. So, you could upgrade that dependency. Or, if this is not possible you can downgrade your jinja version where the escape is still included. You can explicitly add this to your requirements.txt

jinja2<3.1.0


2. We learn from jinja's release that Markup and escape should be imported from Markusafe. You can import escape from MarkupSafe. So you should use this: 

from markupsafe import escape

Hope this solves your error. If you have any questions you can comment below.