I would like to add a hook to Python's Tornado web server such that I can execute some async cleanup function whenever the server is going down for whatever reason.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To add a hook to Python's Tornado web server for executing an asynchronous cleanup function whenever the server is shutting down, you can leverage Tornado's IOLoop and its shutdown handling capabilities. Here's a step-by-step guide to achieve this:
1. Define Your Async Cleanup Function
First, define the asynchronous cleanup function you want to execute when the server shuts down.
python
import asyncio
async def cleanup():
print("Cleanup: Server is shutting down. Performing cleanup tasks...")
# Add your cleanup tasks here, e.g., closing database connections, saving state, etc.
await asyncio.sleep(1) # Simulate an async task
print("Cleanup: Tasks completed.")
2. Add a Shutdown Hook to the IOLoop
Tornado's IOLoop allows you to register a callback that will be executed when the loop is shutting down. You can use this to trigger your cleanup function.
python
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
class MainHandler(RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return Application([
(r"/", MainHandler),
])
def main():
app = make_app()
app.listen(8888)
# Register the cleanup function to be called on shutdown
async def on_shutdown():
await cleanup()
IOLoop.current().add_shutdown_callback(on_shutdown)
print("Server started on port 8888")
IOLoop.current().start()
if __name__ == "__main__":
main()
3. Triggering Shutdown
To test the cleanup function, you can manually stop the server using a keyboard interrupt (Ctrl+C) or programmatically stop the IOLoop.
python
# Example of programmatically stopping the server
import signal
def signal_handler(sig, frame):
print("Received shutdown signal. Stopping the server...")
IOLoop.current().stop()
# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
Full Example
Here’s the complete code:
python
import asyncio
import signal
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
async def cleanup():
print("Cleanup: Server is shutting down. Performing cleanup tasks...")
await asyncio.sleep(1) # Simulate an async task
print("Cleanup: Tasks completed.")
class MainHandler(RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return Application([
(r"/", MainHandler),
])
def main():
app = make_app()
app.listen(8888)
async def on_shutdown():
await cleanup()
IOLoop.current().add_shutdown_callback(on_shutdown)
def signal_handler(sig, frame):
print("Received shutdown signal. Stopping the server...")
IOLoop.current().stop()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
print("Server started on port 8888")
IOLoop.current().start()
if __name__ == "__main__":
main()
Explanation:
add_shutdown_callback: This method of IOLoop registers a callback that will be executed when the IOLoop is shutting down.
Signal Handling: The signal_handler function is registered to handle SIGINT (Ctrl+C) and SIGTERM signals, allowing graceful shutdown.
Async Cleanup: The cleanup function is an asynchronous function that performs any necessary cleanup tasks before the server fully shuts down.
This setup ensures that your cleanup function runs whenever the server shuts down, regardless of the reason.