Flask fails with "Error: While importing 'X', an ImportError was raised", but does not display the error. How to find the source of the error?

Viewed 3972

When starting a Flask app with:

$ flask run

I received the error:

Error: While importing 'wsgi', an ImportError was raised.

Usage: flask [OPTIONS] COMMAND [ARGS]...`
...

However, there is no stack trace or other information provided. What is the best way to get the ImportError stack trace?

3 Answers

Import the Flask app at the Python interpreter prompt

To see the ImportError stack trace, open a Python interpreter prompt and import the module that loads the Flask app (usually app.py or wsgi.py). If applicable, be sure that your virtual environment is activated.

$ python
>>> from my_app_folder import app

Set the FLASK_APP environment variable

If you can import the Flask app module using the Python interpreter without error, try setting the FLASK_APP environment variable to point to the Flask app module.

$ FLASK_APP='my_app_folder/app' FLASK_ENV=development flask run

This error can be caused if Flask is unable to import any libraries(in my case it was Flask_restful)

This is the workaround I found to find the missing libraries:-

I found which library was missing by just running the Flask App file (wsgi.py) directly with python

    python wsgi.py

which gave an Importerror listing the missing libraries

after finding the missing libraries, simply install libraries using pip, for me Flask_restful was missing so I installed Flask_restful . After installing missing libraries simply run the flask app using

    flask run

The only thing that I would add to Christopher Peisert's answer is the option that gave me the error messages that I was searching for:

(venv) ~/example_flask_app/$ python
>>> import app

Or in my case

>>> import microblog
Related