Hosting Static Flask Sites on Github Pages

This past weekend, I released KillTheYak.com, a website with guides for installing and using various tools. It's a static site powered by Flask and hosted for free (as in beer) on Github Pages.

Static Flask sites are a big win because:

  • They're fast.
  • If you need your site to be dynamic in the future, the transition will be easy.
  • There are well-developed extensions for doing this. Here I'll demonstrate Frozen-Flask (for building static content) and Flask-FlatPages (for writing pages in Markdown).

Source for the example site here: sloria/flask-ghpages-example. Live site here: http://stevenloria.com/flask-ghpages-example

App structure

App structure

project/settings.py

Key bits:

  • L19: Tell Frozen-Flask to build the static content to the project root instead of the default build/ directory.
  • L22: We also need to explicitly set FREEZER_BASE_URL since Github Pages hosts your repo pages on http://username.github.com/your-reponame.
  • L23: Don't delete all your app files!
  • L26-27: Tell FlatPages to look for .md files in the project/pages/ directory.

project/app.py

  • This is where the Flask app, pages, and freezer instances live.

project/views.py

  • The page(path) view retrieves a page object and passes it to the template.

project/pages/bacon.md (Page example)

  • The first lines are YAML metadata. They can be accessed in views via the page.meta dict. For example, page.meta['title']. They're also accessible in the templates, as we'll see next.
  • L2: Dates are parsed by PyYAML as datetime objects.

project/templates/page.html

project/main.py

This just imports app, pages, and freezer, and views so that they can be accessed without circular imports (source).

freeze.py

  • This builds the static content to the project root.

Deployment

After creating your Github repo, run the following:

That's it!

See also:

Please send comments by email. I welcome your feedback, advice, and criticism.