So recently I have been jumping into the world of Python and creating my own servers etc now that I felt like I had a grasp of the language.
Coming from Javascript with NodeJS using nodemon, ts-node-dev etc. First thing I wanted in this server was for it to auto reload on changes.
So lets jump right into it.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, Nice!'
if __name__ == '__main__':
app.run('0.0.0.0', 8085)
So this is just your standard Hello World server. The main difference is there is a little check to determine if the file is being executed itself or not.
So using our favorite IDE (In my case PyCharm) we are able to execute that file and the server would run with
* 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://0.0.0.0:8085/ (Press CTRL+C to quit)
We now want to run this with a debugger and for it to reload automagically on changes. To do so you can generally just run (you can one line this I just like multi):
export FLASK_APP=app.py export FLASK_ENV=development flask run --port 8085
However that would become tedious to have to do that every time. So in my project folder I created a /bin
directory and added a server-debug.sh script with the following:
#!/bin/bash
export FLASK_APP=app.py
export FLASK_ENV=development
flask run --port 8085
Now I can then execute the above script via the IDE which will set everything up for me that I could want. This will now output:
* Serving Flask app "app.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 294-871-031 * Running on http://127.0.0.1:8085/ (Press CTRL+C to quit)
Which means we can then go and attach to the debugging process now created, then our breakpoints will work, with the benefit of reloading on changes!
The power of this is that I can now create different executable scripts depending on my needs and not have to worry about it.
Hopefully this helped someone and any improvements I welcome any feedback!
Discussion
Thanks! you´re helping a lot with this post