Starting my Flask app using:
flask run
Doesn't appear to work... and I get the error message:
Error: While importing 'entry', an ImportError was raised.
however if I run:
python entry.py
The app will build successfully? Why is this? Both FLASK_APP and FLASK_ENV are set correctly, here is my folder structure:
entry.py:
from application import create_app
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
application/init.py:
import os
from flask import Flask
from config import DevConfig, TestConfig, ProdConfig
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from application.models import Report
def create_app(testing=False):
app = Flask(__name__)
flask_env = os.getenv("FLASK_ENV", None)
# Configure the application, depending on the environment
if testing:
app.config.from_object(TestConfig)
elif flask_env == "development":
app.config.from_object(DevConfig)
elif flask_env == "production":
app.config.from_object(ProdConfig)
else:
raise ValueError("FLASK_ENV is not set or there is an unknown environment type!")
# init plugins, if any
db.init_app(app)
if flask_env == "development":
with app.app_context():
db.create_all()
db.session.commit()
# register blueprints
register_blueprints(app)
return app
def register_blueprints(app):
from application.main import main_blueprint
app.register_blueprint(main_blueprint)
CodePudding user response:
If you want to start the application through the flask executable, then you have to consider that flask will look for the app.py file containing the app application, if not (as in your case), then you will have to correctly set the value of the environment variable FLASK_APP, which will be equal to FLASK_APP=entry.py:app
On Linux, macOS:
$ export FLASK_APP=entry.py:app
$ flask run
On Windows:
$ set FLASK_APP=entry.py:app
$ flask run
Take a look here: Run The Application.
Here, however, it is explained how flask looks for the application to run
In this case (python entry.py
) everything works correctly, because flask is invoked via python inside the main section, which instead is not called if entry.py is executed directly from flask, in fact flask will not enter the main section, but will look for the app.py file and the app variable inside it. (Obviously it will look for entry.py and app if you have configured the environment variable correctly)