Tornado is a Python web framework and asynchronous networking library designed for applications requiring long-lived connections to many users.
Core web framework components including request handlers, applications, routing, and HTTP utilities. These form the foundation for building web applications with Tornado.
Base class for handling HTTP requests with support for all HTTP methods, argument parsing, response generation, and template rendering.
class RequestHandler:
"""Base class for HTTP request handlers."""
def get(self):
"""Handle GET requests."""
def post(self):
"""Handle POST requests."""
def put(self):
"""Handle PUT requests."""
def delete(self):
"""Handle DELETE requests."""
def patch(self):
"""Handle PATCH requests."""
def head(self):
"""Handle HEAD requests."""
def options(self):
"""Handle OPTIONS requests."""
def get_argument(self, name: str, default=None, strip: bool = True) -> str:
"""
Get argument from query string or request body.
Args:
name: Argument name
default: Default value if argument not found
strip: Whether to strip whitespace
Returns:
Argument value as string
Raises:
MissingArgumentError: If argument not found and no default
"""
def get_arguments(self, name: str, strip: bool = True) -> List[str]:
"""Get list of arguments with given name."""
def get_body_argument(self, name: str, default=None, strip: bool = True) -> str:
"""Get argument from request body (POST data)."""
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]:
"""Get list of body arguments with given name."""
def get_query_argument(self, name: str, default=None, strip: bool = True) -> str:
"""Get argument from query string."""
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
"""Get list of query arguments with given name."""
def write(self, chunk):
"""Write chunk to output buffer."""
def render(self, template_name: str, **kwargs):
"""Render template with given arguments."""
def redirect(self, url: str, permanent: bool = False, status: int = None):
"""
Redirect to given URL.
Args:
url: URL to redirect to
permanent: Whether redirect is permanent (301 vs 302)
status: HTTP status code for redirect
"""
def set_status(self, status_code: int, reason: str = None):
"""Set HTTP status code for response."""
def set_header(self, name: str, value):
"""Set response header."""
def add_header(self, name: str, value):
"""Add response header (allows multiple values)."""
def get_header(self, name: str, default=None) -> str:
"""Get request header value."""
def set_cookie(self, name: str, value: str, domain: str = None, expires=None, path: str = "/", expires_days: int = None, **kwargs):
"""Set cookie in response."""
def get_cookie(self, name: str, default=None) -> str:
"""Get cookie value from request."""
def clear_cookie(self, name: str, path: str = "/", domain: str = None):
"""Clear cookie in response."""
def set_signed_cookie(self, name: str, value: str, expires_days: int = 30, version: int = None, **kwargs):
"""Set signed cookie for security."""
def get_signed_cookie(self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None) -> str:
"""Get signed cookie value."""
def get_current_user(self):
"""Override to implement authentication."""
def xsrf_token(self) -> str:
"""Get XSRF token for form protection."""
def check_xsrf_cookie(self):
"""Verify XSRF token."""
def prepare(self):
"""Called before HTTP method handler."""
def finish(self, chunk=None):
"""Finish request and send response."""
def on_finish(self):
"""Called after request completes."""
def on_connection_close(self):
"""Called when client connection closes."""
def static_url(self, path: str, include_host: bool = None, **kwargs) -> str:
"""Generate URL for static file."""
def reverse_url(self, name: str, *args) -> str:
"""Generate URL from named handler."""
def render_string(self, template_name: str, **kwargs) -> bytes:
"""Render template to string."""
def create_signed_value(self, name: str, value: str, version: int = None) -> str:
"""Create signed value."""
def data_received(self, chunk: bytes):
"""Handle streaming request body data (with @stream_request_body)."""Application class that maps URLs to request handlers and manages application-wide settings and configuration.
class Application:
"""Web application mapping URLs to handlers."""
def __init__(self, handlers=None, default_host: str = "", transforms=None, **settings):
"""
Initialize application.
Args:
handlers: List of URL patterns and handlers
default_host: Default hostname
transforms: Output transforms
**settings: Application settings
"""
def listen(self, port: int, address: str = "", **kwargs):
"""
Start HTTP server on given port.
Args:
port: Port number to listen on
address: Address to bind to (default all interfaces)
**kwargs: Additional server options
"""
def add_handlers(self, host_pattern: str, host_handlers):
"""Add handlers for specific host pattern."""
def reverse_url(self, name: str, *args) -> str:
"""Generate URL from named handler."""
def find_handler(self, request, **kwargs):
"""Find handler for request."""URL routing system for mapping request paths to handlers with support for path parameters and host-based routing.
class URLSpec:
"""URL specification mapping pattern to handler."""
def __init__(self, pattern: str, handler, kwargs=None, name: str = None):
"""
Initialize URL spec.
Args:
pattern: URL pattern (regex)
handler: Handler class
kwargs: Handler initialization arguments
name: Named route for reverse URL generation
"""
class Router:
"""HTTP routing interface."""
def find_handler(self, request, **kwargs):
"""Find handler for request."""
class ReversibleRouter(Router):
"""Router with URL reversal support."""
def reverse_url(self, name: str, *args) -> str:
"""Generate URL from route name."""Built-in handlers for common scenarios like errors, redirects, and static files.
class ErrorHandler(RequestHandler):
"""Default handler for HTTP errors."""
def initialize(self, status_code: int):
"""Initialize with status code."""
class RedirectHandler(RequestHandler):
"""Handler that redirects to another URL."""
def initialize(self, url: str, permanent: bool = True):
"""Initialize with redirect URL."""
class StaticFileHandler(RequestHandler):
"""Handler for serving static files."""
def initialize(self, path: str, default_filename: str = None):
"""Initialize with file path."""
@classmethod
def get_content_type(cls, abspath: str) -> str:
"""Get MIME type for file."""
class FallbackHandler(RequestHandler):
"""Handler that falls back to another application."""
def initialize(self, fallback):
"""Initialize with fallback application."""Decorators for request handlers providing authentication, URL manipulation, and request body streaming.
def authenticated(method):
"""
Decorator requiring user authentication.
Handler must implement get_current_user() method.
"""
def removeslash(method):
"""Decorator to remove trailing slash from URLs."""
def addslash(method):
"""Decorator to add trailing slash to URLs."""
def stream_request_body(method):
"""
Decorator for streaming request body handling.
Handler must implement data_received() and prepare() methods.
"""Functions for creating and verifying signed cookies for secure session management.
def create_signed_value(secret: str, name: str, value: str, version: int = None, clock=None, key_version: int = None) -> str:
"""
Create signed cookie value.
Args:
secret: Secret key for signing
name: Cookie name
value: Cookie value
version: Signature version
clock: Time function
key_version: Key version
Returns:
Signed cookie value
"""
def decode_signed_value(secret: str, name: str, value: str, max_age_days: int = 31, clock=None, min_version: int = None) -> str:
"""
Decode and verify signed cookie value.
Args:
secret: Secret key for verification
name: Cookie name
value: Signed cookie value
max_age_days: Maximum age in days
clock: Time function
min_version: Minimum signature version
Returns:
Original cookie value if valid, None otherwise
"""Reusable UI components for templates that can encapsulate HTML, CSS, and JavaScript.
class UIModule:
"""Base class for reusable template components."""
def __init__(self, handler):
"""Initialize with request handler."""
def render(self, *args, **kwargs) -> str:
"""Render module HTML."""
def embedded_css(self) -> str:
"""Return CSS for this module."""
def embedded_javascript(self) -> str:
"""Return JavaScript for this module."""
def css_files(self) -> List[str]:
"""Return list of CSS files."""
def javascript_files(self) -> List[str]:
"""Return list of JavaScript files."""# Handler initialization arguments
HandlerInitArgs = Dict[str, Any]
# URL pattern type
URLPattern = Tuple[str, Type[RequestHandler], HandlerInitArgs, str]
# Application settings
AppSettings = Dict[str, Any]
# Cookie options
CookieOptions = Dict[str, Any]class HTTPError(Exception):
"""Exception for HTTP errors."""
def __init__(self, status_code: int, log_message: str = None, *args, **kwargs):
"""
Initialize HTTP error.
Args:
status_code: HTTP status code
log_message: Message to log
*args: Additional arguments
**kwargs: Additional keyword arguments
"""
class Finish(Exception):
"""Exception to finish request without additional response."""
class MissingArgumentError(HTTPError):
"""Exception when required argument is missing."""Install with Tessl CLI
npx tessl i tessl/pypi-tornado