0
# Web Framework Core
1
2
Core web framework components including request handlers, applications, routing, and HTTP utilities. These form the foundation for building web applications with Tornado.
3
4
## Capabilities
5
6
### Request Handlers
7
8
Base class for handling HTTP requests with support for all HTTP methods, argument parsing, response generation, and template rendering.
9
10
```python { .api }
11
class RequestHandler:
12
"""Base class for HTTP request handlers."""
13
14
def get(self):
15
"""Handle GET requests."""
16
17
def post(self):
18
"""Handle POST requests."""
19
20
def put(self):
21
"""Handle PUT requests."""
22
23
def delete(self):
24
"""Handle DELETE requests."""
25
26
def patch(self):
27
"""Handle PATCH requests."""
28
29
def head(self):
30
"""Handle HEAD requests."""
31
32
def options(self):
33
"""Handle OPTIONS requests."""
34
35
def get_argument(self, name: str, default=None, strip: bool = True) -> str:
36
"""
37
Get argument from query string or request body.
38
39
Args:
40
name: Argument name
41
default: Default value if argument not found
42
strip: Whether to strip whitespace
43
44
Returns:
45
Argument value as string
46
47
Raises:
48
MissingArgumentError: If argument not found and no default
49
"""
50
51
def get_arguments(self, name: str, strip: bool = True) -> List[str]:
52
"""Get list of arguments with given name."""
53
54
def get_body_argument(self, name: str, default=None, strip: bool = True) -> str:
55
"""Get argument from request body (POST data)."""
56
57
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]:
58
"""Get list of body arguments with given name."""
59
60
def get_query_argument(self, name: str, default=None, strip: bool = True) -> str:
61
"""Get argument from query string."""
62
63
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
64
"""Get list of query arguments with given name."""
65
66
def write(self, chunk):
67
"""Write chunk to output buffer."""
68
69
def render(self, template_name: str, **kwargs):
70
"""Render template with given arguments."""
71
72
def redirect(self, url: str, permanent: bool = False, status: int = None):
73
"""
74
Redirect to given URL.
75
76
Args:
77
url: URL to redirect to
78
permanent: Whether redirect is permanent (301 vs 302)
79
status: HTTP status code for redirect
80
"""
81
82
def set_status(self, status_code: int, reason: str = None):
83
"""Set HTTP status code for response."""
84
85
def set_header(self, name: str, value):
86
"""Set response header."""
87
88
def add_header(self, name: str, value):
89
"""Add response header (allows multiple values)."""
90
91
def get_header(self, name: str, default=None) -> str:
92
"""Get request header value."""
93
94
def set_cookie(self, name: str, value: str, domain: str = None, expires=None, path: str = "/", expires_days: int = None, **kwargs):
95
"""Set cookie in response."""
96
97
def get_cookie(self, name: str, default=None) -> str:
98
"""Get cookie value from request."""
99
100
def clear_cookie(self, name: str, path: str = "/", domain: str = None):
101
"""Clear cookie in response."""
102
103
def set_signed_cookie(self, name: str, value: str, expires_days: int = 30, version: int = None, **kwargs):
104
"""Set signed cookie for security."""
105
106
def get_signed_cookie(self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None) -> str:
107
"""Get signed cookie value."""
108
109
def get_current_user(self):
110
"""Override to implement authentication."""
111
112
def xsrf_token(self) -> str:
113
"""Get XSRF token for form protection."""
114
115
def check_xsrf_cookie(self):
116
"""Verify XSRF token."""
117
118
def prepare(self):
119
"""Called before HTTP method handler."""
120
121
def finish(self, chunk=None):
122
"""Finish request and send response."""
123
124
def on_finish(self):
125
"""Called after request completes."""
126
127
def on_connection_close(self):
128
"""Called when client connection closes."""
129
130
def static_url(self, path: str, include_host: bool = None, **kwargs) -> str:
131
"""Generate URL for static file."""
132
133
def reverse_url(self, name: str, *args) -> str:
134
"""Generate URL from named handler."""
135
136
def render_string(self, template_name: str, **kwargs) -> bytes:
137
"""Render template to string."""
138
139
def create_signed_value(self, name: str, value: str, version: int = None) -> str:
140
"""Create signed value."""
141
142
def data_received(self, chunk: bytes):
143
"""Handle streaming request body data (with @stream_request_body)."""
144
```
145
146
### Web Applications
147
148
Application class that maps URLs to request handlers and manages application-wide settings and configuration.
149
150
```python { .api }
151
class Application:
152
"""Web application mapping URLs to handlers."""
153
154
def __init__(self, handlers=None, default_host: str = "", transforms=None, **settings):
155
"""
156
Initialize application.
157
158
Args:
159
handlers: List of URL patterns and handlers
160
default_host: Default hostname
161
transforms: Output transforms
162
**settings: Application settings
163
"""
164
165
def listen(self, port: int, address: str = "", **kwargs):
166
"""
167
Start HTTP server on given port.
168
169
Args:
170
port: Port number to listen on
171
address: Address to bind to (default all interfaces)
172
**kwargs: Additional server options
173
"""
174
175
def add_handlers(self, host_pattern: str, host_handlers):
176
"""Add handlers for specific host pattern."""
177
178
def reverse_url(self, name: str, *args) -> str:
179
"""Generate URL from named handler."""
180
181
def find_handler(self, request, **kwargs):
182
"""Find handler for request."""
183
```
184
185
### URL Routing
186
187
URL routing system for mapping request paths to handlers with support for path parameters and host-based routing.
188
189
```python { .api }
190
class URLSpec:
191
"""URL specification mapping pattern to handler."""
192
193
def __init__(self, pattern: str, handler, kwargs=None, name: str = None):
194
"""
195
Initialize URL spec.
196
197
Args:
198
pattern: URL pattern (regex)
199
handler: Handler class
200
kwargs: Handler initialization arguments
201
name: Named route for reverse URL generation
202
"""
203
204
class Router:
205
"""HTTP routing interface."""
206
207
def find_handler(self, request, **kwargs):
208
"""Find handler for request."""
209
210
class ReversibleRouter(Router):
211
"""Router with URL reversal support."""
212
213
def reverse_url(self, name: str, *args) -> str:
214
"""Generate URL from route name."""
215
```
216
217
### Error Handling
218
219
Built-in handlers for common scenarios like errors, redirects, and static files.
220
221
```python { .api }
222
class ErrorHandler(RequestHandler):
223
"""Default handler for HTTP errors."""
224
225
def initialize(self, status_code: int):
226
"""Initialize with status code."""
227
228
class RedirectHandler(RequestHandler):
229
"""Handler that redirects to another URL."""
230
231
def initialize(self, url: str, permanent: bool = True):
232
"""Initialize with redirect URL."""
233
234
class StaticFileHandler(RequestHandler):
235
"""Handler for serving static files."""
236
237
def initialize(self, path: str, default_filename: str = None):
238
"""Initialize with file path."""
239
240
@classmethod
241
def get_content_type(cls, abspath: str) -> str:
242
"""Get MIME type for file."""
243
244
class FallbackHandler(RequestHandler):
245
"""Handler that falls back to another application."""
246
247
def initialize(self, fallback):
248
"""Initialize with fallback application."""
249
```
250
251
### Decorators
252
253
Decorators for request handlers providing authentication, URL manipulation, and request body streaming.
254
255
```python { .api }
256
def authenticated(method):
257
"""
258
Decorator requiring user authentication.
259
260
Handler must implement get_current_user() method.
261
"""
262
263
def removeslash(method):
264
"""Decorator to remove trailing slash from URLs."""
265
266
def addslash(method):
267
"""Decorator to add trailing slash to URLs."""
268
269
def stream_request_body(method):
270
"""
271
Decorator for streaming request body handling.
272
273
Handler must implement data_received() and prepare() methods.
274
"""
275
```
276
277
### Cookie Security
278
279
Functions for creating and verifying signed cookies for secure session management.
280
281
```python { .api }
282
def create_signed_value(secret: str, name: str, value: str, version: int = None, clock=None, key_version: int = None) -> str:
283
"""
284
Create signed cookie value.
285
286
Args:
287
secret: Secret key for signing
288
name: Cookie name
289
value: Cookie value
290
version: Signature version
291
clock: Time function
292
key_version: Key version
293
294
Returns:
295
Signed cookie value
296
"""
297
298
def decode_signed_value(secret: str, name: str, value: str, max_age_days: int = 31, clock=None, min_version: int = None) -> str:
299
"""
300
Decode and verify signed cookie value.
301
302
Args:
303
secret: Secret key for verification
304
name: Cookie name
305
value: Signed cookie value
306
max_age_days: Maximum age in days
307
clock: Time function
308
min_version: Minimum signature version
309
310
Returns:
311
Original cookie value if valid, None otherwise
312
"""
313
```
314
315
### UI Modules
316
317
Reusable UI components for templates that can encapsulate HTML, CSS, and JavaScript.
318
319
```python { .api }
320
class UIModule:
321
"""Base class for reusable template components."""
322
323
def __init__(self, handler):
324
"""Initialize with request handler."""
325
326
def render(self, *args, **kwargs) -> str:
327
"""Render module HTML."""
328
329
def embedded_css(self) -> str:
330
"""Return CSS for this module."""
331
332
def embedded_javascript(self) -> str:
333
"""Return JavaScript for this module."""
334
335
def css_files(self) -> List[str]:
336
"""Return list of CSS files."""
337
338
def javascript_files(self) -> List[str]:
339
"""Return list of JavaScript files."""
340
```
341
342
## Types
343
344
```python { .api }
345
# Handler initialization arguments
346
HandlerInitArgs = Dict[str, Any]
347
348
# URL pattern type
349
URLPattern = Tuple[str, Type[RequestHandler], HandlerInitArgs, str]
350
351
# Application settings
352
AppSettings = Dict[str, Any]
353
354
# Cookie options
355
CookieOptions = Dict[str, Any]
356
```
357
358
## Exceptions
359
360
```python { .api }
361
class HTTPError(Exception):
362
"""Exception for HTTP errors."""
363
364
def __init__(self, status_code: int, log_message: str = None, *args, **kwargs):
365
"""
366
Initialize HTTP error.
367
368
Args:
369
status_code: HTTP status code
370
log_message: Message to log
371
*args: Additional arguments
372
**kwargs: Additional keyword arguments
373
"""
374
375
class Finish(Exception):
376
"""Exception to finish request without additional response."""
377
378
class MissingArgumentError(HTTPError):
379
"""Exception when required argument is missing."""
380
```