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>
If we execute the Python script it will generate the following HTML: ~bash $ python blog.py <!doctype html>
-
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!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.