Exploring Tornado Request Handlers and Template Rendering

Output Handling in Tornado

1. Writing Response Data

The write() method buffers output data. Multiple calls append content:


class MainHandler(RequestHandler):
    def get(self):
        self.write("First line")
        self.write("Second line")
        self.write("Third line")

2. JSON Response Handling

Tornado automatically serializes dictionaries to JSON:


class DataHandler(RequestHandler):
    def get(self):
        response = {
            "username": "johndoe",
            "level": 42,
            "active": True
        }
        self.write(response)  # Auto JSON serialization

3. Custom Headers

Set response headers manually:


class ApiHandler(RequestHandler):
    def get(self):
        data = {"status": "success"}
        self.write(json.dumps(data))
        self.set_header("Content-Type", "application/json")

4. Default Headers

Configure default headers for all requests:


class BaseHandler(RequestHandler):
    def set_default_headers(self):
        self.set_header("X-Framework", "Tornado")
        self.set_header("Cache-Control", "no-cache")

Template System

1. Template Configuration

Set template directory path:


app = Application(
    handlers=[...],
    template_path=os.path.join(BASE_DIR, "templates")
)

2. Template Variables

Pass variables to templates:


class ProfileHandler(RequestHandler):
    def get(self):
        context = {
            "user": "admin",
            "permissions": ["read", "write"]
        }
        self.render("profile.html", **context)

3. Control Structures

Conditionals and loops in templates:


{% if items %}
    {% for item in items %}
        <div>{{ item }}</div>
    {% end %}
{% else %}
    <p>No items found</p>
{% end %}

4. Template Inheritance

Base template (base.html):


<html>
{% block head %}{% end %}
{% block content %}{% end %}
</html>

Child template:


{% extends "base.html" %}

{% block head %}
    <title>My Page</title>
{% end %}

{% block content %}
    <h1>Welcome</h1>
{% end %}

5. Static Files

Configure static file handling:


app = Application(
    [...],
    static_path=os.path.join(BASE_DIR, "static"),
    static_url_prefix="/assets/"
)

Use in templates:


<link href="{{ static_url('css/style.css') }}">

Tags: tornado request-handler template-rendering json-response http-headers

Posted on Thu, 09 Jul 2026 17:00:24 +0000 by msmith29063