Flask auto-reload functionality not working with Pycharm Remote Deployment - python

It's hard to remember when, but at one point the auto-reload function of Flask started to not work anymore in my project.
This is the output upon starting my app :
FLASK_APP = back/python/app/app.py:app
FLASK_ENV = development
FLASK_DEBUG = 1
In folder C:/path/to/project
ssh://[VirtualMachineIP]:22/root/env/bin/python3.7 -u -m flask run -h 0.0.0.0 -p 1234
* Serving Flask app 'back/python/app/app.py:app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://[VirtualMachineIP]:1234/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 106-048-128
The development environment and Debug mode are both on. Thus, upon saving changes in a file (while the app is deployed) I get the usual message :
* Detected change in '/path/to/changed/file.py', reloading
Signaling that the app is reloading with the new code. Except it doesn't reload anything, and the message doesn't appear on any further changes until I'm forced to restart the app.
PyCharms runs on Windows and communicates via ssh to my Virtual Machine, where the code is executed. I have installed the following modules:
flask
flask-socketio
eventlet
flask-cors
Any help is welcomed. Thanks :)

The FLASK_DEBUG environment variable is badly supported, it may not behave as expected if set in code. (Quoted from the source of flask).
It suggest to use flask run in debug mode.
eg: $ flask --app hello --debug run
If it still not work, you can force to use reloader like this:
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=True)
Take care, the app.run() must be wrapped with if __name__ == '__main__'.
doc: https://flask.palletsprojects.com/en/2.2.x/config/#DEBUG

Related

Internal Server Error while executing a flask module [duplicate]

How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?
Running the app in debug mode will show an interactive traceback and console in the browser when there is an error. As of Flask 2.2, to run in debug mode, pass the --app and --debug options to the flask command.
$ flask --app example --debug run
Prior to Flask 2.2, this was controlled by the FLASK_ENV=development environment variable instead. You can still use FLASK_APP and FLASK_DEBUG=1 instead of the options above.
For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:
$ export FLASK_APP=example
$ export FLASK_DEBUG=1
$ flask run
For Windows CMD, use set instead of export:
set FLASK_DEBUG=1
For PowerShell, use $env:
$env:FLASK_DEBUG = "1"
If you're using the app.run() method instead of the flask run command, pass debug=True to enable debug mode.
Tracebacks are also printed to the terminal running the server, regardless of development mode.
If you're using PyCharm, VS Code, etc., you can take advantage of its debugger to step through the code with breakpoints. The run configuration can point to a script calling app.run(debug=True, use_reloader=False), or point it at the venv/bin/flask script and use it as you would from the command line. You can leave the reloader disabled, but a reload will kill the debugging context and you will have to catch a breakpoint again.
You can also use pdb, pudb, or another terminal debugger by calling set_trace in the view where you want to start debugging.
Be sure not to use too-broad except blocks. Surrounding all your code with a catch-all try... except... will silence the error you want to debug. It's unnecessary in general, since Flask will already handle exceptions by showing the debugger or a 500 error and printing the traceback to the console.
You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.
From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:
export FLASK_APP=/daemon/api/views.py # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
One can also use the Flask Debug Toolbar extension to get more detailed information embedded in rendered pages.
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
import logging
app = Flask(__name__)
app.debug = True
app.secret_key = 'development key'
toolbar = DebugToolbarExtension(app)
#app.route('/')
def index():
logging.warning("See this message in Flask Debug Toolbar!")
return "<html><body></body></html>"
Start the application as follows:
FLASK_APP=main.py FLASK_DEBUG=1 flask run
If you're using Visual Studio Code, replace
app.run(debug=True)
with
app.run()
It appears when turning on the internal debugger disables the VS Code debugger.
If you want to debug your flask app then just go to the folder where flask app is. Don't forget to activate your virtual environment and paste the lines in the console change "mainfilename" to flask main file.
export FLASK_APP="mainfilename.py"
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0
After you enable your debugger for flask app almost every error will be printed on the console or on the browser window.
If you want to figure out what's happening, you can use simple print statements or you can also use console.log() for javascript code.
To activate debug mode in flask you simply type set FLASK_DEBUG=1 on your CMD for windows, or export FLASK_DEBUG=1 on Linux terminal then restart your app and you are good to go!!
Install python-dotenv in your virtual environment.
Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file
Inside this file write the following:
FLASK_APP=myapp
FLASK_ENV=development
Now issue the following command:
flask run
When running as python app.py instead of the flask command, you can pass debug=True to app.run.
if __name__ == "__main__":
app.run(debug=True)
$ python app.py
with virtual env activate
export FLASK_DEBUG=true
you can configure
export FLASK_APP=app.py # run.py
export FLASK_ENV = "development"
to start
flask run
the result
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: xxx-xxx-xxx
and if you change
export FLASK_DEBUG=false
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
For Windows users:
Open Powershell and cd into your project directory.
Use these commandos in Powershell, all the other stuff won't work in Powershell.
$env:FLASK_APP = "app"
$env:FLASK_ENV = "development"
If you have PyCharm Professional, you can create a Flask server run configuration and enable the FLASK_DEBUG checkbox. Go to Run > Edit Configurations, select or create a Flask server configuration, and enable the FLASK_DEBUG checkbox. Click OK, then click the run button.
You can install python-dotenv with
pip install python-dotenv then create a .flask_env or a .env file
The contents of the file can be:
FLASK_APP=myapp
FLASK_DEBUG=True
Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.

Name error depending on debug mode of python flask application

When running the flask app 'app.py' without debug mode, everything runs fine:
app = Flask(__name__)
#app.route("/")
def home():
return "Hey there"
if __name__=="__main__":
app.run()
Server startign:
* Serving Flask app 'app' (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: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When running the Flask app in debug mode
app.run(debug=True) I'll get "No module named app" error and the server won't start:
* Serving Flask app 'app' (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
No module named app
I have noticed that when starting the script in vsCode without debug mode (ctrl+f5) or press the button 'Run Python File' everything works fine.
When I start debugging (f5) in vsCode the 'No module named app' occurs and after the failed server start I jump back to the parent folder (app.py is in /folder/app/app.py - after server start failed I am in the terminal in the '/folder' rather then '/folder/app' like before starting the script.
Does anyone got an idea where the problem is? Appreciate any help
The problem can be resolved by adding a launch.json file to the workspace and adding either an absolute to your app.py file:
"cwd":"path/to/folder/"
or a relative path to the directory of the executed script:
"cwd":"${fileDirname}"

Is there a way to run flask in debug mode using the `flask run` command without setting environment variables?

I'm trying to run a flask application in debug mode (or at least a mode where it will reload after changing the files).
I'm aware of export FLASK_ENV=development, however I am working on a university online development environment, and I lose the environment variables every time the site reloads, which while not the end of the world, is slightly annoying, and I'd rather avoid having to keep typing it (lazy I know).
If I include the following, and run using python3 main.py, debug mode is activated, however when using flask run, debug remains off.
if __name__ == "__main__":
app.run(debug=True)
However, as I understand it, using the flask run command is the preferred way to launch the app, not using python app.py.
I've found ideas such as including the following, however none of these have activated debug mode, so I'm wondering whether it is even possible:
app.config['ENV'] = 'development'
app.config['DEBUG'] = True
app.config['TESTING'] = True
I've simplified my code to the following to see if it was an error in my original piece, but it doesn't seem to be:
from flask import Flask
app = Flask(__name__)
app.config['ENV'] = 'development'
app.config['DEBUG'] = True
app.config['TESTING'] = True
#app.route('/')
def home():
return '<h1>debugging!</h1>'
if __name__ == "__main__":
app.run(debug=True)
In short, there does not seem to be a way of using flask run how I want without assigning environment variables, however using a .flaskenv file will allow environment variables to be loaded at run time.
The .flaskenv file for example could include the following ENVs among others to be loaded:
FLASK_APP=main:app
FLASK_ENV=development
FLASK_DEBUG=1
Note - this does require python-dotenv to be installed to use.
All credit to #cizario who answered here with some more detail:
https://stackoverflow.com/a/64623193/12368419
Well, when it's Flask 2.2 or later, you can just do
flask --debug run
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 560-342-853

Running Flask by "flask run" vs running from editor (Windows 10)

If I run my Flask app through the command "flask run", not only the arguments in app.run are ignored (making debugger false and choosing the default port 5000), but changes made to the script too, e.g. changing url_prefix to "/views". The cmd prompt won't even respond when I save the script after making alterations. This way, changes are only effective after stopping the script then running again.
This doesn't happen when the app script is ran through VSCode commands (Ctrl+F5 or the play button): through those, the script is executed as written and changes are recognized right after saving a script.
Why is that so?
from flask import Flask
from views import views
app = Flask(__name__)
app.register_blueprint(views, url_prefix="/")
if __name__ == '__main__':
app.run(debug=True, port=8000)
C:\Users\*******\Documents\flask_quick_website>flask run
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
The flask executable works by importing the app object from your code. This is similar to how a WSGI server like gunicorn works (research what this is if you're unsure).
As for when you run the script with VSCode, or in-fact if you launch with the python executable by running python app.py or similar, then anything inside the if __name__ == '__main__': block is executed, in your case the app.run call.
Also note your app.run call is passed the debug=True argument. If you investigate the Flask source code, inside the run function, the use_reloader argument is set to the same value as debug so in this case the auto-reloader runs if debug is True.
So how to make the auto-reloader work with the flask command? Pass the --reload flag:
flask run --reload
You can also set the environment to development to achieve the same. On windows:
> set FLASK_ENV=development
> flask run
See Environment and Debug features for more on this.

Trying to run flask with the following code [duplicate]

This question already has answers here:
Warning message while running Flask
(12 answers)
Closed 2 years ago.
from flask import Flask
app = Flask(_name_)
#app.route('/')
def index():
return '<h1>Hello, world</h1>'
I get this error
* Serving Flask app "application.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
This is just a warning as flask server is not meant for production.
You can use
export FLASK_ENV=development
before flask run
It depends if you are running it from command line or adding python code to run it.
If you want to run it with Python, add this to the bottom of your code.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
(you can change the port number, to access it on a browser, type: 127.0.0.1:80)
If you are running it from command line, you run
flask run
Note this appears every time:
Serving Flask app "application.py" * Environment: production WARNING:
This is a development server. Do not use it in a production
deployment. Use a production WSGI server instead. * Debug mode: off
All it tells you is that this server is only used for development or production. Hosting it for commercial/public use would require additional files and web hosting.
You can allow debugging to be on with
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, DEBUG=True)
OR
export FLASK_ENV=development (linux/macos)
set FLASK_ENV=development (Windows)
Hope this helps (follow me on GitHub #haydenso)

Categories

Resources