import tornado
Hello World¶
Start a small web app on port 8889 (Jupyter itself usually listens on 8888). The handler is synchronous; it does not use tornado's native async capabilities.
A notebook already runs an asyncio event loop, so app.listen() is enough: the server answers requests in the background while the kernel is idle. In a standalone script, put the two last lines in an async def main() that ends with await asyncio.Event().wait(), and call asyncio.run(main()).
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
app = make_app()
server = app.listen(8889)
Sync¶
HTTPClient is the blocking client, meant for code that does not run an event loop. It starts its own loop, which cannot run on the notebook's thread while the notebook's loop is running, so this cell calls it from a worker thread.
import asyncio
from tornado.httpclient import HTTPClient
def synchronous_fetch(url):
http_client = HTTPClient()
response = http_client.fetch(url)
return response.body
body = await asyncio.to_thread(synchronous_fetch, "https://google.com")
body[:100]
Async coroutine¶
Await the coroutine directly; the notebook's event loop runs it. The second call fetches the Hello World app started above.
from tornado.httpclient import AsyncHTTPClient
async def asynchronous_fetch(url):
http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
return response.body
body = await asynchronous_fetch("https://google.com")
print(body[:100])
print(await asynchronous_fetch("http://localhost:8889/"))
Tornado and Uvloop and Asyncio¶
Tornado runs on any asyncio event loop, including uvloop. A notebook already runs its own loop, so this example is for a standalone script:
import asyncio
import tornado.web
import uvloop
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
async def main():
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8888)
await asyncio.Event().wait()
uvloop.run(main())