draft = false date="2017-04-27 20:59:56" title="Python: Flask - Generating a static HTML page" tag=['python'] category=['Python'] description="Learn how to generate a static HTML page using Python's Flask library."

Whenever I need to quickly spin up a web application Python’s Flask library is my go to tool but I recently found myself wanting to generate a static HTML to upload to S3 and wondered if I could use it for that as well.

It’s actually not too tricky. If we’re in the scope of the app context then we have access to the template rendering that we’d normally use when serving the response to a web request.

The following code will generate a HTML file based on a template file</a> templates/blog.html: </p> ~python from flask import render_template import flask app = flask.Flask('my app') if name == "main": with app.app_context(): rendered = render_template('blog.html', \ title = "My Generated Page", \ people = [{"name": "Mark"}, {"name": "Michael"}]) print(rendered) ~

templates/blog.html ~html <!doctype html> {{ title }}* {{ person.name }} ~

If we execute the Python script it will generate the following HTML: ~bash $ python blog.py <!doctype html> My Generated Page= My Generated Page

  • Mark

  • Michael ~

And we can finish off by redirecting that output into a file: ~bash $ python blog.py > generated_blog.html ~

We could also write to the file from Python but this seems just as easy!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket