'Flask - Error: While importing 'app', an ImportError was raised
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
Solution 1:[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:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GerritKruse |
| Solution 2 | sbmthakur |
