Flask教程运行报错:无法导入flaskr.flaskr(NoAppException)
Hey there, let's work through this Flask app issue step by step—this error is super common when getting started with the Flask 1.0 tutorial, so we'll get it sorted out.
First, let's break down the error
The flask.cli.NoAppException: Could not import "flaskr.flaskr" message tells us Flask is trying to import a module called flaskr.flaskr instead of just flaskr. This usually boils down to directory structure or command execution context issues.
Here are the fixes to try, in order of likelihood:
1. Double-check your project directory structure
The Flask 1.0 tutorial expects a nested directory setup like this:
flaskr/ # Outer project root directory venv/ # Your virtual environment flaskr/ # Inner package directory (this is the actual Flask app) __init__.py # Other tutorial files (like auth.py, blog.py later on)
If you put your __init__.py directly in the outer flaskr directory (instead of the inner subdirectory), Flask will misinterpret the package structure and look for flaskr.flaskr instead of the correct flaskr package. Fix this structure if needed.
2. Run commands from the correct directory
You must execute your export and flask run commands from the outer flaskr directory (the one that contains the inner flaskr package and your venv folder).
If you run the commands from inside the inner flaskr directory, Flask will treat that folder as the root and try to import flaskr.flaskr (which doesn't exist), hence the error.
3. Verify your __init__.py has the right structure
Flask 1.0's tutorial uses the application factory pattern, so your inner flaskr/__init__.py needs to have a create_app() function. It should look something like this:
from flask import Flask def create_app(): app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' return app
Without this function, Flask can't properly load your application. If you skipped this part or structured the app differently, adjust the file to match the tutorial's pattern.
4. Confirm your virtual environment dependencies are correct
While Flask 1.0.2 is fully compatible with Python 3.6.0, let's double-check your virtual environment setup:
- Activate your venv first:
source venv/bin/activate - Verify Flask's version:
pip show Flask - If the version isn't 1.0.2, reinstall it:
pip install Flask==1.0.2
5. Try specifying the absolute path for FLASK_APP (optional)
If the above steps don't work, you can force Flask to use the correct path by setting FLASK_APP to the absolute path of your inner flaskr package:
export FLASK_APP=/full/path/to/your/outer-flaskr-directory/flaskr export FLASK_ENV=development flask run
Most of the time, fixing the directory structure or running commands from the right folder resolves this error immediately. Give these steps a shot, and you should see that "Hello, World!" message in no time.
内容的提问来源于stack exchange,提问作者DavidGodwin

