0
# Tornado
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: tornado
7
- **Language**: Python
8
- **Installation**: `pip install tornado`
9
- **Python Requirements**: >= 3.9
10
11
## Core Imports
12
13
```python
14
import tornado
15
# tornado.version - Version string (e.g., "6.5.2")
16
# tornado.version_info - Version tuple (e.g., (6, 5, 2, 0))
17
```
18
19
For web applications:
20
21
```python
22
import tornado.web
23
import tornado.ioloop
24
```
25
26
For HTTP clients:
27
28
```python
29
import tornado.httpclient
30
```
31
32
For WebSocket applications:
33
34
```python
35
import tornado.websocket # Direct import required
36
```
37
38
## Basic Usage
39
40
### Simple Web Application
41
42
```python
43
import tornado.ioloop
44
import tornado.web
45
46
class MainHandler(tornado.web.RequestHandler):
47
def get(self):
48
self.write("Hello, world")
49
50
def make_app():
51
return tornado.web.Application([
52
(r"/", MainHandler),
53
])
54
55
if __name__ == "__main__":
56
app = make_app()
57
app.listen(8888)
58
tornado.ioloop.IOLoop.current().start()
59
```
60
61
### HTTP Client Usage
62
63
```python
64
import tornado.httpclient
65
import tornado.ioloop
66
67
async def fetch_example():
68
http_client = tornado.httpclient.AsyncHTTPClient()
69
try:
70
response = await http_client.fetch("http://www.example.com/")
71
print(response.body)
72
except Exception as e:
73
print(f"Error: {e}")
74
finally:
75
http_client.close()
76
77
if __name__ == "__main__":
78
tornado.ioloop.IOLoop.current().run_sync(fetch_example)
79
```
80
81
### WebSocket Server
82
83
```python
84
import tornado.ioloop
85
import tornado.web
86
import tornado.websocket
87
88
class EchoWebSocket(tornado.websocket.WebSocketHandler):
89
def open(self):
90
print("WebSocket opened")
91
92
def on_message(self, message):
93
self.write_message(f"Echo: {message}")
94
95
def on_close(self):
96
print("WebSocket closed")
97
98
app = tornado.web.Application([
99
(r"/websocket", EchoWebSocket),
100
])
101
102
if __name__ == "__main__":
103
app.listen(8888)
104
tornado.ioloop.IOLoop.current().start()
105
```
106
107
## Architecture
108
109
Tornado's architecture centers around asynchronous, non-blocking I/O:
110
111
- **IOLoop**: Core event loop managing all asynchronous operations
112
- **Web Framework**: Request handlers and routing for HTTP applications
113
- **Async Streams**: Non-blocking I/O abstractions for network operations
114
- **HTTP Client/Server**: Full HTTP protocol implementation
115
- **WebSocket Support**: Native WebSocket protocol handling
116
117
The framework is built around Python's async/await syntax and provides a complete stack for building scalable web applications and network services.
118
119
## Capabilities
120
121
### Web Framework Core
122
123
Core web framework components including request handlers, applications, routing, and HTTP utilities. These form the foundation for building web applications with Tornado.
124
125
```python { .api }
126
class RequestHandler:
127
def get(self): ...
128
def post(self): ...
129
def put(self): ...
130
def delete(self): ...
131
def patch(self): ...
132
def head(self): ...
133
def options(self): ...
134
def prepare(self): ...
135
def on_finish(self): ...
136
def get_argument(self, name: str, default=None, strip: bool = True) -> str: ...
137
def get_arguments(self, name: str, strip: bool = True) -> List[str]: ...
138
def get_body_argument(self, name: str, default=None, strip: bool = True) -> str: ...
139
def get_query_argument(self, name: str, default=None, strip: bool = True) -> str: ...
140
def write(self, chunk): ...
141
def render(self, template_name: str, **kwargs): ...
142
def redirect(self, url: str, permanent: bool = False, status: int = None): ...
143
def set_status(self, status_code: int, reason: str = None): ...
144
def set_header(self, name: str, value: str): ...
145
def get_cookie(self, name: str, default: str = None) -> str: ...
146
def set_cookie(self, name: str, value: str, **options): ...
147
def set_signed_cookie(self, name: str, value: str, expires_days: int = 30, **kwargs): ...
148
def get_signed_cookie(self, name: str, value: str = None, max_age_days: int = 31) -> str: ...
149
def get_current_user(self): ...
150
def xsrf_token(self) -> str: ...
151
def check_xsrf_cookie(self): ...
152
153
class Application:
154
def __init__(self, handlers=None, default_host: str = None, **settings): ...
155
def listen(self, port: int, address: str = "", **kwargs): ...
156
def add_handlers(self, host_pattern: str, host_handlers): ...
157
def reverse_url(self, name: str, *args) -> str: ...
158
159
def authenticated(method): ...
160
def stream_request_body(cls): ...
161
```
162
163
[Web Framework Core](./web-framework.md)
164
165
### HTTP Client and Server
166
167
HTTP client for making requests and HTTP server for handling incoming connections. Supports both synchronous and asynchronous operations with comprehensive HTTP feature support.
168
169
```python { .api }
170
class AsyncHTTPClient:
171
def fetch(self, request, raise_error: bool = True, **kwargs): ...
172
def close(self): ...
173
174
class HTTPClient:
175
def __init__(self, async_client_class=None, **kwargs): ...
176
def fetch(self, request, **kwargs) -> HTTPResponse: ...
177
def close(self): ...
178
179
class HTTPServer:
180
def listen(self, port: int, address: str = ""): ...
181
def start(self, num_processes: int = 1): ...
182
def stop(self): ...
183
184
class HTTPRequest:
185
def __init__(self, url: str, method: str = "GET", headers=None, body=None,
186
connect_timeout: float = None, request_timeout: float = None, **kwargs): ...
187
188
class HTTPResponse:
189
def __init__(self, request: HTTPRequest, code: int, headers=None, buffer=None, **kwargs): ...
190
def rethrow(self): ...
191
192
class HTTPClientError(Exception):
193
def __init__(self, code: int, message: str = None, response: HTTPResponse = None): ...
194
```
195
196
[HTTP Client and Server](./http-client-server.md)
197
198
### WebSocket Support
199
200
Full WebSocket protocol implementation for real-time, bidirectional communication between client and server. Supports both server-side handlers and client connections.
201
202
```python { .api }
203
class WebSocketHandler:
204
def open(self, *args, **kwargs): ...
205
def on_message(self, message: Union[str, bytes]): ...
206
def on_close(self): ...
207
def write_message(self, message: Union[str, bytes, Dict], binary: bool = False): ...
208
def close(self, code: int = None, reason: str = None): ...
209
def ping(self, data: bytes = b""): ...
210
def on_ping(self, data: bytes): ...
211
def on_pong(self, data: bytes): ...
212
def check_origin(self, origin: str) -> bool: ...
213
214
class WebSocketClientConnection:
215
def write_message(self, message: Union[str, bytes, Dict], binary: bool = False): ...
216
def read_message(self): ...
217
def close(self, code: int = None, reason: str = None): ...
218
219
def websocket_connect(url: str, on_message_callback=None,
220
connect_timeout: float = None, **kwargs) -> WebSocketClientConnection: ...
221
222
class WebSocketError(Exception): ...
223
class WebSocketClosedError(WebSocketError): ...
224
```
225
226
[WebSocket Support](./websocket.md)
227
228
### Asynchronous I/O
229
230
Core asynchronous I/O primitives including event loops, streams, locks, queues, and futures. These components enable non-blocking operations and concurrent programming patterns.
231
232
```python { .api }
233
class IOLoop:
234
# Event constants
235
NONE = 0
236
READ = 0x001
237
WRITE = 0x004
238
ERROR = 0x018
239
240
@classmethod
241
def current(cls, instance: bool = True): ...
242
@classmethod
243
def configure(cls, impl, **kwargs): ...
244
def start(self): ...
245
def stop(self): ...
246
def close(self, all_fds: bool = False): ...
247
def run_sync(self, func, timeout: float = None): ...
248
def add_callback(self, callback, *args, **kwargs): ...
249
def add_timeout(self, deadline, callback, *args, **kwargs): ...
250
def call_later(self, delay: float, callback, *args, **kwargs): ...
251
def add_handler(self, fd, handler, events): ...
252
def remove_handler(self, fd): ...
253
def time(self) -> float: ...
254
255
class PeriodicCallback:
256
def __init__(self, callback, callback_time: float, jitter: float = 0): ...
257
def start(self): ...
258
def stop(self): ...
259
def is_running(self) -> bool: ...
260
261
class IOStream:
262
def read_bytes(self, num_bytes: int, callback=None): ...
263
def read_until(self, delimiter: bytes, callback=None): ...
264
def write(self, data: bytes, callback=None): ...
265
def close(self): ...
266
267
class Lock:
268
async def acquire(self): ...
269
def release(self): ...
270
```
271
272
[Asynchronous I/O](./async-io.md)
273
274
### Networking Utilities
275
276
Low-level networking utilities for TCP connections, DNS resolution, and socket operations. Provides the foundation for custom network protocols and services.
277
278
```python { .api }
279
class TCPServer:
280
def listen(self, port: int, address: str = ""): ...
281
def start(self, num_processes: int = 1): ...
282
def handle_stream(self, stream, address): ...
283
284
class TCPClient:
285
async def connect(self, host: str, port: int, **kwargs): ...
286
287
def bind_sockets(port: int, address: str = None, family=socket.AF_INET, backlog: int = 128): ...
288
```
289
290
[Networking Utilities](./networking.md)
291
292
### Authentication
293
294
Authentication and authorization support for third-party services including OAuth, OAuth2, OpenID, and integration with major providers like Google, Facebook, and Twitter.
295
296
```python { .api }
297
class OAuthMixin:
298
def get_auth_http_client(self): ...
299
300
class OAuth2Mixin:
301
def authorize_redirect(self, redirect_uri: str, client_id: str, **kwargs): ...
302
303
class GoogleOAuth2Mixin: ...
304
class FacebookGraphMixin: ...
305
class TwitterMixin: ...
306
```
307
308
[Authentication](./authentication.md)
309
310
### Template Engine
311
312
Server-side template engine with automatic escaping, inheritance, and integration with the web framework. Supports both file-based and in-memory templates.
313
314
```python { .api }
315
class Template:
316
def __init__(self, template_string: str, name: str = "<string>", **kwargs): ...
317
def generate(self, **kwargs) -> bytes: ...
318
319
class Loader:
320
def __init__(self, root_directory: str, **kwargs): ...
321
def load(self, name: str, parent_path: str = None) -> Template: ...
322
```
323
324
[Template Engine](./templates.md)
325
326
### Testing Utilities
327
328
Comprehensive testing support for asynchronous code including test case classes, HTTP test servers, and async test decorators. Integrates with standard Python testing frameworks.
329
330
```python { .api }
331
class AsyncTestCase:
332
def setUp(self): ...
333
def tearDown(self): ...
334
335
class AsyncHTTPTestCase:
336
def get_app(self): ...
337
def get_http_client(self): ...
338
def get_url(self, path: str): ...
339
340
def gen_test(func=None, timeout: float = None): ...
341
```
342
343
[Testing Utilities](./testing.md)
344
345
### Utilities and Configuration
346
347
Utility functions, configuration management, logging, localization, process management, and string processing utilities that support the core framework functionality.
348
349
```python { .api }
350
# Configuration and options
351
def define(name: str, default=None, type_=None, help: str = None): ...
352
def parse_command_line(): ...
353
354
# String escaping and encoding
355
def url_escape(value: str, plus: bool = True) -> str: ...
356
def json_encode(value) -> str: ...
357
def json_decode(value: str): ...
358
359
# Logging
360
def enable_pretty_logging(options=None, logger=None): ...
361
362
# Process management
363
def fork_processes(num_processes: int, max_restarts: int = 100): ...
364
```
365
366
[Utilities and Configuration](./utilities.md)
367
368
## Types
369
370
```python { .api }
371
# Core imports for types
372
from typing import List, Dict, Union, Optional, Callable, Any, Awaitable
373
import socket
374
375
# HTTP types
376
HTTPHeaders = Dict[str, str]
377
378
# Web framework types
379
class HTTPError(Exception):
380
def __init__(self, status_code: int, log_message: str = None, *args, **kwargs): ...
381
382
class MissingArgumentError(HTTPError):
383
def __init__(self, arg_name: str): ...
384
385
# HTTP client types
386
class HTTPClientError(Exception):
387
def __init__(self, code: int, message: str = None, response: Optional[HTTPResponse] = None): ...
388
389
HTTPError = HTTPClientError # Alias for backward compatibility
390
391
# Stream types
392
class StreamClosedError(Exception): ...
393
394
# WebSocket types
395
class WebSocketError(Exception): ...
396
class WebSocketClosedError(WebSocketError): ...
397
398
# Template types
399
class TemplateNotFound(Exception): ...
400
401
# Authentication types
402
class AuthError(Exception): ...
403
```