tornado
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Top Related Projects
Asynchronous HTTP client/server framework for asyncio and Python
The Python micro framework for building web applications.
The Web framework for perfectionists with deadlines.
The little ASGI framework that shines. 🌟
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Accelerate your web app development | Build fast. Run fast.
Quick Overview
Tornado is a Python web framework and asynchronous networking library. It uses non-blocking network I/O to scale to tens of thousands of open connections, making it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each user.
Pros
- High performance and scalability for handling many concurrent connections
- Built-in support for WebSockets and long polling
- Asynchronous programming model for efficient I/O operations
- Lightweight and flexible, with minimal external dependencies
Cons
- Steeper learning curve compared to synchronous frameworks like Flask or Django
- Smaller ecosystem and fewer third-party extensions than more popular frameworks
- Not as suitable for traditional CRUD applications or content-heavy websites
- Requires careful consideration of asynchronous programming patterns
Code Examples
- Basic Hello World application:
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()
- Asynchronous HTTP client:
from tornado.httpclient import AsyncHTTPClient
from tornado import ioloop
async def fetch_url(url):
http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
print(f"Fetched {url}, status code: {response.code}")
async def main():
await fetch_url("http://example.com")
ioloop.IOLoop.current().run_sync(main)
- WebSocket handler:
import tornado.websocket
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message(f"You said: {message}")
def on_close(self):
print("WebSocket closed")
Getting Started
To get started with Tornado, follow these steps:
-
Install Tornado:
pip install tornado
-
Create a new Python file (e.g.,
app.py
) and add the following code:import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, Tornado!") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8000) print("Server running on http://localhost:8000") tornado.ioloop.IOLoop.current().start()
-
Run the application:
python app.py
-
Open a web browser and visit
http://localhost:8000
to see your Tornado application in action.
Competitor Comparisons
Asynchronous HTTP client/server framework for asyncio and Python
Pros of aiohttp
- Built on top of asyncio, providing a more modern and flexible asynchronous framework
- Supports both client and server-side HTTP, making it versatile for various use cases
- Extensive ecosystem with many third-party libraries and extensions
Cons of aiohttp
- Steeper learning curve, especially for developers new to asyncio
- Less mature and battle-tested compared to Tornado's long history
- May require more boilerplate code for certain tasks
Code Comparison
aiohttp server example:
from aiohttp import web
async def hello(request):
return web.Response(text="Hello, World!")
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)
Tornado server example:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Both aiohttp and Tornado are powerful asynchronous web frameworks for Python. aiohttp is more modern and flexible, leveraging asyncio, while Tornado has a longer history and may be easier for beginners. The choice between them depends on specific project requirements and developer preferences.
The Python micro framework for building web applications.
Pros of Flask
- Simpler and more lightweight, making it easier to learn and use for beginners
- More flexible and customizable, allowing developers to choose their preferred components
- Larger ecosystem with a wide range of extensions available
Cons of Flask
- Less performant for handling concurrent connections compared to Tornado
- Lacks built-in asynchronous support, requiring additional libraries for async operations
Code Comparison
Flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
Tornado:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('Hello, World!')
app = tornado.web.Application([(r'/', MainHandler)])
Both frameworks offer simple ways to create web applications, but Tornado's code structure is more oriented towards handling asynchronous operations. Flask's syntax is more straightforward and easier to read for beginners, while Tornado's approach provides better support for scalable, non-blocking applications.
The Web framework for perfectionists with deadlines.
Pros of Django
- Full-featured web framework with built-in admin interface, ORM, and authentication system
- Large ecosystem with extensive third-party packages and plugins
- Excellent documentation and strong community support
Cons of Django
- Heavier and more opinionated, which can be overkill for smaller projects
- Steeper learning curve for beginners due to its comprehensive nature
- Slower performance compared to lightweight frameworks like Tornado
Code Comparison
Django:
from django.http import HttpResponse
from django.urls import path
def hello(request):
return HttpResponse("Hello, World!")
urlpatterns = [
path('hello/', hello),
]
Tornado:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
app = tornado.web.Application([
(r"/hello", MainHandler),
])
Both frameworks allow for easy routing and handling of HTTP requests, but Django's approach is more declarative, while Tornado's is more object-oriented. Django's built-in features make it easier to set up a complete web application quickly, whereas Tornado's lightweight nature allows for more fine-grained control and better performance in certain scenarios.
The little ASGI framework that shines. 🌟
Pros of Starlette
- Lightweight and modular design, allowing for easy customization
- Built-in support for WebSocket and GraphQL
- Excellent performance, especially for async applications
Cons of Starlette
- Less mature ecosystem compared to Tornado
- Fewer built-in features, requiring additional libraries for some functionalities
- Steeper learning curve for developers new to ASGI
Code Comparison
Tornado:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
if __name__ == "__main__":
application = tornado.web.Application([(r"/", MainHandler)])
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
Starlette:
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
async def homepage(request):
return PlainTextResponse("Hello, World!")
app = Starlette(debug=True, routes=[
Route("/", homepage),
])
Both Tornado and Starlette are popular Python web frameworks, but they cater to different use cases. Tornado is a more established framework with a rich set of built-in features, while Starlette offers a modern, lightweight approach with excellent async performance. The choice between the two depends on specific project requirements and developer preferences.
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Pros of FastAPI
- Built-in support for asynchronous programming and modern Python features (3.6+)
- Automatic API documentation with Swagger UI and ReDoc
- Type hints and data validation out of the box
Cons of FastAPI
- Steeper learning curve for developers new to type annotations and Pydantic
- Relatively young project compared to Tornado's maturity
- Heavier dependency on external libraries (e.g., Starlette, Pydantic)
Code Comparison
FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Tornado:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write({"message": "Hello World"})
app = tornado.web.Application([(r"/", MainHandler)])
FastAPI offers a more concise syntax and built-in support for JSON responses, while Tornado requires more boilerplate code but provides finer-grained control over request handling.
Accelerate your web app development | Build fast. Run fast.
Pros of Sanic
- Faster performance due to its asynchronous nature and use of uvloop
- Built-in support for WebSockets and streaming responses
- More modern API design with better support for async/await syntax
Cons of Sanic
- Less mature and stable compared to Tornado
- Smaller ecosystem and community support
- Limited compatibility with older Python versions (requires Python 3.7+)
Code Comparison
Sanic:
from sanic import Sanic
from sanic.response import json
app = Sanic("MyApp")
@app.route("/")
async def test(request):
return json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Tornado:
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(8000)
tornado.ioloop.IOLoop.current().start()
Both frameworks provide asynchronous web server capabilities, but Sanic offers a more modern and streamlined API. Tornado, while slightly more verbose, has a longer history and broader ecosystem support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Tornado Web Server
.. image:: https://badges.gitter.im/Join%20Chat.svg :alt: Join the chat at https://gitter.im/tornadoweb/tornado :target: https://gitter.im/tornadoweb/tornado?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
Tornado <http://www.tornadoweb.org>
_ is a Python web framework and
asynchronous networking library, originally developed at FriendFeed <http://friendfeed.com>
. By using non-blocking network I/O, Tornado
can scale to tens of thousands of open connections, making it ideal for
long polling <http://en.wikipedia.org/wiki/Push_technology#Long_Polling>
,
WebSockets <http://en.wikipedia.org/wiki/WebSocket>
_, and other
applications that require a long-lived connection to each user.
Hello, world
Here is a simple "Hello, world" example web app for Tornado:
.. code-block:: python
import asyncio
import tornado
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
async def main():
app = make_app()
app.listen(8888)
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())
This example does not use any of Tornado's asynchronous features; for
that see this simple chat room <https://github.com/tornadoweb/tornado/tree/stable/demos/chat>
_.
Documentation
Documentation and links to additional resources are available at https://www.tornadoweb.org
Top Related Projects
Asynchronous HTTP client/server framework for asyncio and Python
The Python micro framework for building web applications.
The Web framework for perfectionists with deadlines.
The little ASGI framework that shines. 🌟
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Accelerate your web app development | Build fast. Run fast.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot