ChatGPT解决这个技术问题 Extra ChatGPT

Auto reloading python Flask app upon code changes

I'm investigating how to develop a decent web app with Python. Since I don't want some high-order structures to get in my way, my choice fell on the lightweight Flask framework. Time will tell if this was the right choice.

So, now I've set up an Apache server with mod_wsgi, and my test site is running fine. However, I'd like to speed up the development routine by making the site automatically reload upon any changes in py or template files I make. I see that any changes in site's .wsgi file causes reloading (even without WSGIScriptReloading On in the apache config file), but I still have to prod it manually (ie, insert extra linebreak, save). Is there some way how to cause reload when I edit some of the app's py files? Or, I am expected to use IDE that refreshes the .wsgi file for me?


d
davidism

The current recommended way is with the flask command line utility.

https://flask.palletsprojects.com/en/1.1.x/quickstart/#debug-mode

Example:

$ export FLASK_APP=main.py
$ export FLASK_ENV=development
$ flask run

or in one command:

$ FLASK_APP=main.py FLASK_ENV=development flask run

If you want different port than the default (5000) add --port option.

Example:

$ FLASK_APP=main.py FLASK_ENV=development flask run --port 8080

More options are available with:

$ flask run --help

FLASK_APP can also be set to module:app or module:create_app instead of module.py. See https://flask.palletsprojects.com/en/1.1.x/cli/#application-discovery for a full explanation.


or pyvenv in python3.5, flask run also works, since when you pip install flask, a flask executable file is also installed in the venv/bin/ folder.
This is a simple solution that can be translated to Docker for development purposes. One can see this same solution here.
Works well normally but this doesn't seem to work on Ubuntu with code on an NTFS partition. Not a problem with the code but flask doesn't seem to recognize changes in that setup.
how does flask know which files you want to watch ?
if I use "sudo pipenv run python3 main.py" to execute my web app, then what I should I type for same hot reload function?
N
Neil

If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.

app.run(debug=True)

Or, from the shell:

$ export FLASK_DEBUG=1
$ flask run

http://flask.pocoo.org/docs/quickstart/#debug-mode


This works only when you run the site via the built-in development server. But not when running it via wsgi, on Apache. And I don't insist I really need to run it on Apache, so maybe what you suggest is the right way to do it.
correct. In dev environment, the built in server works really well and you don't need to reinvent the wheel for reloading the app. I strongly advise you just use the built in server for dev. purposes. In prod anyway, you don't want to auto reload the app at every code change.
E
Ewan

In test/development environments

The werkzeug debugger already has an 'auto reload' function available that can be enabled by doing one of the following:

app.run(debug=True)

or

app.debug = True

You can also use a separate configuration file to manage all your setup if you need be. For example I use 'settings.py' with a 'DEBUG = True' option. Importing this file is easy too;

app.config.from_object('application.settings')

However this is not suitable for a production environment.

Production environment

Personally I chose Nginx + uWSGI over Apache + mod_wsgi for a few performance reasons but also the configuration options. The touch-reload option allows you to specify a file/folder that will cause the uWSGI application to reload your newly deployed flask app.

For example, your update script pulls your newest changes down and touches 'reload_me.txt' file. Your uWSGI ini script (which is kept up by Supervisord - obviously) has this line in it somewhere:

touch-reload = '/opt/virtual_environments/application/reload_me.txt'

I hope this helps!


Thanks for the great tip. I simplified it a bit. Create a bash script that touches itself when executed. Thus you only need to launch it when you want a reload. My solution: # touch_me_and_reload.sh touch $0
@Ewan. where is the touch-reload line supposed to be in? the [program:uwsig] section or the [supervisord] section?
@user805981- neither, a separate uwsgi configuration .ini file. If you read the documentation on "touch-reload" it's in the uWSGI, not supervisor, configuration.
Thanks for this. app.run(debug=True) fails, but setting the environmental variable works.
K
Kyle James Walker

If you're running using uwsgi look at the python auto reload option:

uwsgi --py-autoreload 1

Example uwsgi-dev-example.ini:

[uwsgi]
socket = 127.0.0.1:5000
master = true
virtualenv = /Users/xxxx/.virtualenvs/sites_env
chdir = /Users/xxx/site_root
module = site_module:register_debug_server()
callable = app
uid = myuser
chmod-socket = 660
log-date = true
workers = 1
py-autoreload = 1

site_root/__init__.py

def register_debug_server():
    from werkzeug.debug import DebuggedApplication

    app = Flask(__name__)
    app.debug = True
    app = DebuggedApplication(app, evalex=True)
    return app

Then run:

uwsgi --ini uwsgi-dev-example.ini

Note: This example also enables the debugger.

I went this route to mimic production as close as possible with my nginx setup. Simply running the flask app with it's built in web server behind nginx it would result in a bad gateway error.


Z
Zach Valenta

A few updates for Flask 1.0 and above

the basic approach to hot re-loading is:

$ export FLASK_APP=my_application
$ export FLASK_ENV=development
$ flask run

you should use FLASK_ENV=development (not FLASK_DEBUG=1)

as a safety check, you can run flask run --debugger just to make sure it's turned on

the Flask CLI will now automatically read things like FLASK_APP and FLASK_ENV if you have an .env file in the project root and have python-dotenv installed


export FLASK_ENV=development worked for me. app.run(debug=True) does not appear to work.
@alex strange behavior
R
Rajat Tyagi
app.run(use_reloader=True)

we can use this, use_reloader so every time we reload the page our code changes will be updated.


A
Anthonyeef

I got a different idea:

First:

pip install python-dotenv

Install the python-dotenv module, which will read local preference for your project environment.

Second:

Add .flaskenv file in your project directory. Add following code:

FLASK_ENV=development

It's done!

With this config for your Flask project, when you run flask run and you will see this output in your terminal:

https://i.stack.imgur.com/cqRV8.png

And when you edit your file, just save the change. You will see auto-reload is there for you:

https://i.stack.imgur.com/WoRS8.png

With more explanation:

Of course you can manually hit export FLASK_ENV=development every time you need. But using different configuration file to handle the actual working environment seems like a better solution, so I strongly recommend this method I use.


Perfect! also, don't forget to include the FLASK_APP variable into the .flaskenv file.
this is the neater and more useful answer... thanks
This works. Thank you.
A
Anandakrishnan

Use this method:

app.run(debug=True)

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
   return "Hello World"


if __name__ == '__main__':
  app.run(debug=True)

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.


P
Paul

From the terminal you can simply say

export FLASK_APP=app_name.py
export FLASK_ENV=development
flask run

or in your file

if __name__ == "__main__":
    app.run(debug=True)

B
Biswajit Roy

Flask applications can optionally be executed in debug mode. In this mode, two very convenient modules of the development server called the reloader and the debugger are enabled by default. When the reloader is enabled, Flask watches all the source code files of your project and automatically restarts the server when any of the files are modified.

By default, debug mode is disabled. To enable it, set a FLASK_DEBUG=1 environment variable before invoking flask run:

(venv) $ export FLASK_APP=hello.py for Windows use > set FLASK_APP=hello.py

(venv) $ export FLASK_DEBUG=1 for Windows use > set FLASK_DEBUG=1

(venv) $ flask run

* Serving Flask app "hello"
* Forcing debug mode on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 273-181-528

Having a server running with the reloader enabled is extremely useful during development, because every time you modify and save a source file, the server automatically restarts and picks up the change.


E
Emma

To achieve this in PyCharm set 'Environment Variables' section to:

PYTHONUNBUFFERED=1;
FLASK_DEBUG=1

For Flask 'run / debug configurations'.


For PyCharm Pro users, you can setup a separate debug config
j
jeffasante

To help with fast automatic change in browser:

pip install livereload

from livereload import Server

if __name__ == '__main__':
    server = Server(app.wsgi_app)
    server.serve()

Next, Start your server again:

eg. your .py file is app.py

python app.py


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now