Flask - Error: While importing 'app', an ImportError was raised

19,046

Solution 1

If your typing here is correct, the error is that the importet module is misspelled (Flask must be uppecase). Here the correct way:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello Wolford"

@app.route("/greeting/")
def greeting():
    return "Nice to see you"

Solution 2

This error is also emitted when there's an error in an imported module. A good way to start debugging such errors is to directly run the file with python (without flask run). Do not forget to call the app function. Just add the following lines if you are using Flask's Application Factory pattern.

if __name__ == "__main__":
    create_app().run()

After that run the app: python app.py

Share:
19,046

Related videos on Youtube

SeattleDucati
Author by

SeattleDucati

Updated on June 04, 2022

Comments

  • SeattleDucati
    SeattleDucati almost 2 years

    I'm trying to get a hello world flask app running with Python 3.9.7.

    Folder structure:
    py-flask/
    app.py
    README.md

    Content of app.py:

    from flask import flask
    
    app = flask(__name__)
    
    @app.route("/")
    def index():
        return "Hello Wolford"
    
    @app.route("/greeting/")
    def greeting():
        return "Nice to see you"
    

    When I am in the py-flask directory, and I try running the app, I get:
    Error: While importing 'app', an ImportError was raised.

    I've tried python3 -m flask run and flask run neither works.

    Any thoughts on what I could be doing wrong?
    pip list if its useful:

    Package       Version
    ------------- -------
    cachelib      0.4.1
    click         8.0.3
    Flask         2.0.2
    Flask-Session 0.4.0
    itsdangerous  2.0.1
    Jinja2        3.0.2
    MarkupSafe    2.0.1
    pip           21.2.3
    setuptools    57.4.0
    Werkzeug      2.0.2
    
    • jluu
      jluu over 2 years
      ending the app.py with the line: app.run() and invoking python app.py will output more usable diagnostics like a stack trace
  • SeattleDucati
    SeattleDucati over 2 years
    That worked. Thank you!!!!!
  • sur.la.route
    sur.la.route over 2 years
    Any ideas on how to get the error message to be more verbose? As it tell you what module had the import error?
  • Solomon Duskis
    Solomon Duskis about 2 years
    To debug this: run python app.py (after adding an app.run() at the end of app.py, if you don't already have it already wrapped in an if __name__ == "__main__":)
  • simanacci
    simanacci about 2 years
    Start a python shell, and try importing app. from app import create_app app = create_app you'll get the error on the terminal.