A Tornado Application connects URL patterns to request handlers, accepts server settings, listens on a port, and runs through Tornado’s event loop. section 5.5.1 section 6.3.1
Build a small robot web service by:
- Installing Tornado on the Raspberry Pi. section 5.5.1
- Defining a RequestHandler method for incoming HTTP GET requests. section 5.5.1
- Registering a route such as / with its handler in Application. section 5.5.1
- Passing settings such as debug mode and the template directory. section 6.3.1
- Starting the server with listen and keeping it active through IOLoop.current().start(). section 5.5.1
Robot time service
A minimal application maps the root path to MainHandler, which returns the robot server’s current time. Running it on port 8888 lets curl retrieve JSON from http://localhost:8888/; the response includes a stamp field and an application/json content type. section 5.5.1
Listing 6.1 basic_web.py: Web application that displays the time on the robot
#!/usr/bin/env python3
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application
from tornado.log import enable_pretty_logging
from datetime import datetime
from os.path import dirname
import os
DEBUG = bool(os.environ.get('ROBO_DEBUG'))
TEMPLATE_PATH = (dirname(__file__) + '/templates')
class MainHandler(RequestHandler):
def get(self):
stamp = datetime.now().isoformat()
self.render('basic.html', stamp=stamp)
enable_pretty_logging()
settings = dict(debug=DEBUG, template_path=TEMPLATE_PATH)
app = Application([('/', MainHandler)], **settings)
app.listen(8888)
IOLoop.current().start()
Open the complete runnable Python service, including imports, handler, debug configuration, template path, route registration, port binding, and event-loop startup. section 6.3.1
