Core Concepts & Application Structure
The tornado.web.Application class is the central component. It maps request handlers to URL patterns.
Example:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
|
tornado.web.RequestHandler
|
Base class for request handlers. Override HTTP method functions (e.g., get() , post() ).
|
|
Writes a chunk of output to the client. Can be called multiple times.
|
self.render(template_name, **kwargs)
|
Renders a template using the given context.
|
self.get_argument(name, default=None, strip=True)
|
Returns the value of the argument with the given name.
|
self.set_header(name, value)
|
|
URL patterns are defined as a list of tuples: (r"/path", HandlerClass, dict(kwargs), name)
r"/path" : Regular expression to match the URL.
HandlerClass : The request handler class to use.
kwargs : A dictionary of keyword arguments to pass to the handler’s initialize method.
name : Name of the route, can be used with reverse_url()
|
Example:
app = tornado.web.Application([
(r"/", MainHandler),
(r"/user/([a-zA-Z0-9]+)", UserHandler, dict(database=db)),
])
|
Asynchronous Operations and IOLoop
The tornado.ioloop.IOLoop is the core of Tornado’s asynchronous execution.
IOLoop.current() - Returns the current IOLoop instance.
IOLoop.start() - Starts the IOLoop, blocking until stop() is called.
IOLoop.stop() - Stops the IOLoop.
|
Example:
tornado.ioloop.IOLoop.current().start()
|
tornado.httpclient.AsyncHTTPClient
|
Non-blocking HTTP client for making asynchronous requests.
|
fetch(request, callback=None, raise_error=True)
|
Performs an HTTP request. Returns a Future if callback is None, otherwise invokes the callback with the HTTPResponse object.
|
|
from tornado.httpclient import AsyncHTTPClient
async def fetch_url(url):
http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
print(response.body.decode())
tornado.ioloop.IOLoop.current().run_sync(lambda: fetch_url("http://www.example.com"))
|
Tornado uses Futures to represent the eventual result of an asynchronous operation.
@tornado.gen.coroutine decorator allows you to write asynchronous code using yield (pre-Python 3.5) or async/await (Python 3.5+).
Example (using async/await ):
import tornado.gen
from tornado.httpclient import AsyncHTTPClient
async def get_example_html():
http_client = AsyncHTTPClient()
response = await http_client.fetch("http://www.example.com")
return response.body.decode()
|