Outputting HTML with Django templates

Zato is a middleware and backend server but at times it still desirable to be able to produce HTML from services. For instance, a set of services performing background batch jobs may output HTML reports for administrators to consult each week.

To use Django templates in responses a service should subclass zato.server.service.internal.helpers.HTMLService and assign HTML output as using self.set_html_payload providing the method with a dictionary of context and a template the context should be rendered in.

Consider the example below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from zato.server.service.internal.helpers import HTMLService

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
  <head>
    <title>Report for {{ report_date }}</title>
  </head>
  <body>
    The result for {{ report_date }} is <strong>{{ result }}</strong>.
  </body>
</html>
"""

class MyReports(HTMLService):

    def handle(self):

        # Obtain current date and assume the imaginary job's result was OK
        ctx = {
            'report_date': self.time.today(),
            'result': 'OK'
        }

        # Set HTML payload, will also produce the Content-Type header
        self.set_html_payload(ctx, HTML_TEMPLATE)

The service can now be mounted on an HTTP channel, possibly secured with HTTP Basic Auth, and invoked from a browser:

../_images/html.png