importerror: cannot import name ‘json’ from ‘itsdangerous’
Cause of importerror: cannot import name ‘json’ from ‘itsdangerous’
One can get this error importerror: cannot import name ‘json’ from ‘itsdangerous’ while getting a Flask and Docker application. Sometimes this results in an import error. While searching for solutions some may encounter that downloading this results in various problems in your system. Another solution people encounter is by creating a virtual environment called veganetworkscriptenv for the purpose of installing the packages but that too does not work properly in some cases.
veganetworkscript-backend-1 | Traceback (most recent call last): veganetworkscript-backend-1 | File "/app/vegamain.py", line 8, in <module> veganetworkscript-backend-1 | from flask import Flask veganetworkscript-backend-1 | File "/usr/local/lib/python3.9/site-packages/flask/__init__.py", line 19, in <module> veganetworkscript-backend-1 | from . import json veganetworkscript-backend-1 | File "/usr/local/lib/python3.9/site-packages/flask/json/__init__.py", line 15, in <module> veganetworkscript-backend-1 | from itsdangerous import json as _json veganetworkscript-backend-1 | ImportError: cannot import name 'json' from 'itsdangerous' (/usr/local/lib/python3.9/site-packages/itsdangerous/__init__.py) veganetworkscript-backend-1 exited with code 1
Solution
The major cause of this problem importerror: cannot import name ‘json’ from ‘itsdangerous’ is not having the latest version of the package. One can solve this by externally adding the latest version of the dangerous package to the requirements.txt file. At last as an effective change, one needs to update the virtual environment as well for making the new file execute.
Upgrading Flask to version 2.0.1 or above is a good idea. It is advised that you use it to resolve the problem. The code for the above is:
pip install Flask=2.0.1
Since it’s challenging to upgrade to the newest Flask version quickly, you can attempt the options listed below to fix the problem.
You can keep using Flask version 1.1.2 while attempting to downgrade the dangerous to 2.0.1. Itsdangerous==2.0.1 can be added to your requirements.txt file to do this.
Another option is to downgrade the markup safe library to 2.0.1 and upgrade Flask from 1.1.2 to 1.1.4, as these are not fundamental changes.
pip install Flask==1.1.4
pip install markupsafe==2.0.1
Also Read: failed to load plugin flowtype declared in package.json