Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python: Flask – Generating a Static HTML Page

DZone's Guide to

Python: Flask – Generating a Static HTML Page

Read on for a quick and easy tutorial on how to use Python's flask library to generate an HTML file and create a static page from there.

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

Whenever I need to quickly spin up a web application, Python’s Flask library is my go to tool. Recently, however, I found myself wanting to generate a static HTML page 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 an 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"}])
        print(rendered)

templates/index.html


<!doctype html>
<html>
  <head>
<title>{{ title }}</title>
  </head>
  <body>
<h1>{{ title }}</h1>
  <ul>
  {% for person in people %}
    <li>{{ person.name }}</li>
  {% endfor %}
  </ul>
  </body>
</html>


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

$ python blog.py 
<!doctype html>
<html>
  <head>
<title>My Generated Page</title>
  </head>
  <body>
<h1>My Generated Page</h1>
  <ul>

    <li>Mark</li>

    <li>Michael</li>

  </ul>

  </body>
</html>


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

$ python blog.py  > blog.html

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

Implementing an Experimentation Solution: Choosing whether to build or buy?

Topics:
web dev ,python ,html

Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}