Python: Flask – Generating a static HTML page

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 templates/blog.html:

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"}])


<!doctype html>
	<title>{{ title }}</title>
	<h1>{{ title }}</h1>
  {% for person in people %}
    <li>{{ }}</li>
  {% endfor %}

If we execute the Python script it will generate the following HTML:

$ python 
<!doctype html>
	<title>My Generated Page</title>
	<h1>My Generated Page</h1>

And we can finish off by redirecting that output into a file:

$ python  > blog.html

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

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook


and many more ....


I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button