One of the most irritating (i would say) things about web development is about restarting your web server whenever there’s a change in the code base or the template files to test if the development change has been propagated correctly… If you’re a web developer you know exactly about the agony I’m referring to… Well, Tornado has something to offer in this realm as well..
tornado.autoreload module automatically detects development changes and restarts the server when a module is modified. Not only that, it can also restart when a monitored file has changed. (File change acts as a trigger) Moreover, the developer can hook into the restart call and execute a method call just before the server restarts. Let’s see all the above features with code snippets.
In this example, tornado.autoreload() re-starts the web server when there is a change in tornadoreload.py file. Sequence of events go like this:
- When user runs tornadoreload.py app, you don’t see any message on command line and ioloop has started.
- On browsing to http://localhost:8000/, Main class handles the GET request and renders ‘Main’ on the web page
- With the web server still running, open another terminal and edit tornadoreload.py to change say ‘Main’ to ‘MainO’
- Refer to the terminal where you are running the server, you would notice a message stating ‘Hooked before reloading…’.
- This is because when tornadoreload.py has changed, web server restarts with tornado.autoreload.start() and also before restarting it calls the hooked function with tornado.autoreload.add_reload_hook(fn) where the method fn() prints the ‘Hooked before reloading…’ message on command line..
- And if you refresh your browser, you would see ‘MainO’ pertaining to the change in tornadoreload.py app
- So as a web developer, you’re free.. 🙂 But restart is destructive and cancels the pending requests..
In this example, we demonstrate how tornado can restart based on a change in watched (monitored) file. Here, the file ‘watch’ is being monitored for change for tornado to restart.. Also note tornado gets restarted when the app and any modules imported in the app are changed.
Many applications built on Tornado don’t use these and often end up using debug=True in tornado.web.Application constructor, which is also useful in detecting changes in module and static file content.