or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-io.mdauthentication.mdhttp-client-server.mdindex.mdnetworking.mdtemplates.mdtesting.mdutilities.mdweb-framework.mdwebsocket.md
tile.json

tessl/pypi-tornado

Tornado is a Python web framework and asynchronous networking library designed for applications requiring long-lived connections to many users.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/tornado@6.5.x

To install, run

npx @tessl/cli install tessl/pypi-tornado@6.5.0

index.mddocs/

Tornado

Tornado is a Python web framework and asynchronous networking library designed for applications requiring long-lived connections to many users. It excels at handling thousands of simultaneous connections through non-blocking network I/O, making it ideal for real-time web services, WebSocket applications, long polling, and other scenarios requiring persistent connections.

Package Information

  • Package Name: tornado
  • Language: Python
  • Installation: pip install tornado
  • Python Requirements: >= 3.9

Core Imports

import tornado
# tornado.version - Version string (e.g., "6.5.2")  
# tornado.version_info - Version tuple (e.g., (6, 5, 2, 0))

For web applications:

import tornado.web
import tornado.ioloop

For HTTP clients:

import tornado.httpclient

For WebSocket applications:

import tornado.websocket  # Direct import required

Basic Usage

Simple Web 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()

HTTP Client Usage

import tornado.httpclient
import tornado.ioloop

async def fetch_example():
    http_client = tornado.httpclient.AsyncHTTPClient()
    try:
        response = await http_client.fetch("http://www.example.com/")
        print(response.body)
    except Exception as e:
        print(f"Error: {e}")
    finally:
        http_client.close()

if __name__ == "__main__":
    tornado.ioloop.IOLoop.current().run_sync(fetch_example)

WebSocket Server

import tornado.ioloop
import tornado.web
import tornado.websocket

class EchoWebSocket(tornado.websocket.WebSocketHandler):
    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        self.write_message(f"Echo: {message}")

    def on_close(self):
        print("WebSocket closed")

app = tornado.web.Application([
    (r"/websocket", EchoWebSocket),
])

if __name__ == "__main__":
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Architecture

Tornado's architecture centers around asynchronous, non-blocking I/O:

  • IOLoop: Core event loop managing all asynchronous operations
  • Web Framework: Request handlers and routing for HTTP applications
  • Async Streams: Non-blocking I/O abstractions for network operations
  • HTTP Client/Server: Full HTTP protocol implementation
  • WebSocket Support: Native WebSocket protocol handling

The framework is built around Python's async/await syntax and provides a complete stack for building scalable web applications and network services.

Capabilities

Web Framework Core

Core web framework components including request handlers, applications, routing, and HTTP utilities. These form the foundation for building web applications with Tornado.

class RequestHandler:
    def get(self): ...
    def post(self): ...
    def put(self): ...
    def delete(self): ...
    def patch(self): ...
    def head(self): ...
    def options(self): ...
    def prepare(self): ...
    def on_finish(self): ...
    def get_argument(self, name: str, default=None, strip: bool = True) -> str: ...
    def get_arguments(self, name: str, strip: bool = True) -> List[str]: ...
    def get_body_argument(self, name: str, default=None, strip: bool = True) -> str: ...
    def get_query_argument(self, name: str, default=None, strip: bool = True) -> str: ...
    def write(self, chunk): ...
    def render(self, template_name: str, **kwargs): ...
    def redirect(self, url: str, permanent: bool = False, status: int = None): ...
    def set_status(self, status_code: int, reason: str = None): ...
    def set_header(self, name: str, value: str): ...
    def get_cookie(self, name: str, default: str = None) -> str: ...
    def set_cookie(self, name: str, value: str, **options): ...
    def set_signed_cookie(self, name: str, value: str, expires_days: int = 30, **kwargs): ...
    def get_signed_cookie(self, name: str, value: str = None, max_age_days: int = 31) -> str: ...
    def get_current_user(self): ...
    def xsrf_token(self) -> str: ...
    def check_xsrf_cookie(self): ...

class Application:
    def __init__(self, handlers=None, default_host: str = None, **settings): ...
    def listen(self, port: int, address: str = "", **kwargs): ...
    def add_handlers(self, host_pattern: str, host_handlers): ...
    def reverse_url(self, name: str, *args) -> str: ...

def authenticated(method): ...
def stream_request_body(cls): ...

Web Framework Core

HTTP Client and Server

HTTP client for making requests and HTTP server for handling incoming connections. Supports both synchronous and asynchronous operations with comprehensive HTTP feature support.

class AsyncHTTPClient:
    def fetch(self, request, raise_error: bool = True, **kwargs): ...
    def close(self): ...

class HTTPClient:
    def __init__(self, async_client_class=None, **kwargs): ...
    def fetch(self, request, **kwargs) -> HTTPResponse: ...
    def close(self): ...

class HTTPServer:
    def listen(self, port: int, address: str = ""): ...
    def start(self, num_processes: int = 1): ...
    def stop(self): ...

class HTTPRequest:
    def __init__(self, url: str, method: str = "GET", headers=None, body=None, 
                 connect_timeout: float = None, request_timeout: float = None, **kwargs): ...

class HTTPResponse:
    def __init__(self, request: HTTPRequest, code: int, headers=None, buffer=None, **kwargs): ...
    def rethrow(self): ...

class HTTPClientError(Exception):
    def __init__(self, code: int, message: str = None, response: HTTPResponse = None): ...

HTTP Client and Server

WebSocket Support

Full WebSocket protocol implementation for real-time, bidirectional communication between client and server. Supports both server-side handlers and client connections.

class WebSocketHandler:
    def open(self, *args, **kwargs): ...
    def on_message(self, message: Union[str, bytes]): ...
    def on_close(self): ...
    def write_message(self, message: Union[str, bytes, Dict], binary: bool = False): ...
    def close(self, code: int = None, reason: str = None): ...
    def ping(self, data: bytes = b""): ...
    def on_ping(self, data: bytes): ...
    def on_pong(self, data: bytes): ...
    def check_origin(self, origin: str) -> bool: ...

class WebSocketClientConnection:
    def write_message(self, message: Union[str, bytes, Dict], binary: bool = False): ...
    def read_message(self): ...
    def close(self, code: int = None, reason: str = None): ...

def websocket_connect(url: str, on_message_callback=None, 
                     connect_timeout: float = None, **kwargs) -> WebSocketClientConnection: ...

class WebSocketError(Exception): ...
class WebSocketClosedError(WebSocketError): ...

WebSocket Support

Asynchronous I/O

Core asynchronous I/O primitives including event loops, streams, locks, queues, and futures. These components enable non-blocking operations and concurrent programming patterns.

class IOLoop:
    # Event constants
    NONE = 0
    READ = 0x001
    WRITE = 0x004
    ERROR = 0x018
    
    @classmethod
    def current(cls, instance: bool = True): ...
    @classmethod
    def configure(cls, impl, **kwargs): ...
    def start(self): ...
    def stop(self): ...
    def close(self, all_fds: bool = False): ...
    def run_sync(self, func, timeout: float = None): ...
    def add_callback(self, callback, *args, **kwargs): ...
    def add_timeout(self, deadline, callback, *args, **kwargs): ...
    def call_later(self, delay: float, callback, *args, **kwargs): ...
    def add_handler(self, fd, handler, events): ...
    def remove_handler(self, fd): ...
    def time(self) -> float: ...

class PeriodicCallback:
    def __init__(self, callback, callback_time: float, jitter: float = 0): ...
    def start(self): ...
    def stop(self): ...
    def is_running(self) -> bool: ...

class IOStream:
    def read_bytes(self, num_bytes: int, callback=None): ...
    def read_until(self, delimiter: bytes, callback=None): ...
    def write(self, data: bytes, callback=None): ...
    def close(self): ...

class Lock:
    async def acquire(self): ...
    def release(self): ...

Asynchronous I/O

Networking Utilities

Low-level networking utilities for TCP connections, DNS resolution, and socket operations. Provides the foundation for custom network protocols and services.

class TCPServer:
    def listen(self, port: int, address: str = ""): ...
    def start(self, num_processes: int = 1): ...
    def handle_stream(self, stream, address): ...

class TCPClient:
    async def connect(self, host: str, port: int, **kwargs): ...

def bind_sockets(port: int, address: str = None, family=socket.AF_INET, backlog: int = 128): ...

Networking Utilities

Authentication

Authentication and authorization support for third-party services including OAuth, OAuth2, OpenID, and integration with major providers like Google, Facebook, and Twitter.

class OAuthMixin:
    def get_auth_http_client(self): ...

class OAuth2Mixin:
    def authorize_redirect(self, redirect_uri: str, client_id: str, **kwargs): ...

class GoogleOAuth2Mixin: ...
class FacebookGraphMixin: ...
class TwitterMixin: ...

Authentication

Template Engine

Server-side template engine with automatic escaping, inheritance, and integration with the web framework. Supports both file-based and in-memory templates.

class Template:
    def __init__(self, template_string: str, name: str = "<string>", **kwargs): ...
    def generate(self, **kwargs) -> bytes: ...

class Loader:
    def __init__(self, root_directory: str, **kwargs): ...
    def load(self, name: str, parent_path: str = None) -> Template: ...

Template Engine

Testing Utilities

Comprehensive testing support for asynchronous code including test case classes, HTTP test servers, and async test decorators. Integrates with standard Python testing frameworks.

class AsyncTestCase:
    def setUp(self): ...
    def tearDown(self): ...

class AsyncHTTPTestCase:
    def get_app(self): ...
    def get_http_client(self): ...
    def get_url(self, path: str): ...

def gen_test(func=None, timeout: float = None): ...

Testing Utilities

Utilities and Configuration

Utility functions, configuration management, logging, localization, process management, and string processing utilities that support the core framework functionality.

# Configuration and options
def define(name: str, default=None, type_=None, help: str = None): ...
def parse_command_line(): ...

# String escaping and encoding
def url_escape(value: str, plus: bool = True) -> str: ...
def json_encode(value) -> str: ...
def json_decode(value: str): ...

# Logging
def enable_pretty_logging(options=None, logger=None): ...

# Process management  
def fork_processes(num_processes: int, max_restarts: int = 100): ...

Utilities and Configuration

Types

# Core imports for types
from typing import List, Dict, Union, Optional, Callable, Any, Awaitable
import socket

# HTTP types
HTTPHeaders = Dict[str, str]

# Web framework types
class HTTPError(Exception):
    def __init__(self, status_code: int, log_message: str = None, *args, **kwargs): ...

class MissingArgumentError(HTTPError):
    def __init__(self, arg_name: str): ...

# HTTP client types  
class HTTPClientError(Exception):
    def __init__(self, code: int, message: str = None, response: Optional[HTTPResponse] = None): ...

HTTPError = HTTPClientError  # Alias for backward compatibility

# Stream types
class StreamClosedError(Exception): ...

# WebSocket types
class WebSocketError(Exception): ...
class WebSocketClosedError(WebSocketError): ...

# Template types
class TemplateNotFound(Exception): ...

# Authentication types
class AuthError(Exception): ...