Home > front end >  Why is app.run with debug mode on not working?
Why is app.run with debug mode on not working?

Time:03-09

I tried to start a Flask application with app.run() in python shell. When I passed debug=False, it worked, but not working with debug=True which gave me the following python error:

>>> from HelloW import app
>>> app.run(debug=True, port=1234)
 * Serving Flask app 'HelloW' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
C:\Users\lfcta\Documents\Python\python.exe: can't find '__main__' module in 'E:\\Flask\\Flask_WTF'

where E:\Flask\Flask_WTF\Hellow.py contains the following code:

from    flask   import Flask

app = Flask(__name__)

@app.route('/home')
def home():
    return '<h2>Hello World!</h2>'

I don't encounter this problem with the "flask run" command regardless of the debug mode.

E:\Flask\Flask_WTF>set flask_app=HelloW.py

E:\Flask\Flask_WTF>set flask_debug=1
E:\Flask\Flask_WTF>flask run // working

E:\Flask\Flask_WTF>set flask_debug=0
E:\Flask\Flask_WTF>flask run // working
 

CodePudding user response:

The problem only occurs when you run the code from an interactive shell. It is caused by a feature in werkzeug (the wsgi server flask is based on).

In debug mode werkzeug will automatically restart your server if a project file is changed. Everytime a change is detected werkzeug restarts the file that was initially started. Even the first start is done via the file name!

But in the interactive shell there is no file at all and werkzeug thinks your file is "" (empty string). It then tries to run that file. For some reason it also thinks that the "" refers to a package. But since that package does not exist it also cannot have a main module, hence the error.

You can simulate that error by running "" directly

python ""

prints: can't find '__main__' module in ''

You could try to disable the reloader by setting debug to False (which is also the default):

app.run(debug=False, ...)

  • Related