Generate an html document with images and text in the python script (without servers if possible)

advertisements

How can I generate HTML containing images and text, using a template and css, in python?

There are few similar questions on stackoverflow (e.g.: Q1, Q2, Q3) but they offer solutions that (to me) seem overkill, like requiring servers (e.g. genshi).

Simple code using django would be as follows:

from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# https://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django

# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""

t = Template(template)
c = Context({"title": "title from code",
             "mystring":"string from code"})
print t.render(c)

(From here: Generating HTML documents in python)

This code produces an error, supposedly because I need to set up a backend:

Traceback (most recent call last):
  File "<input>", line 17, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/base.py", line 184, in __init__
    engine = Engine.get_default()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/template/engine.py", line 81, in get_default
    "No DjangoTemplates backend is configured.")
django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured.

Is there a simple way to have a template.html and style.css and a bunch of images, and use data in a python script to replace placeholders in the template.html without having to set up a server?


There are quite a few python template engines - for a start you may want to have a look here : https://wiki.python.org/moin/Templating

As far as I'm concerned I'd use jinja2 but YMMV.