Skip to content

Instantly share code, notes, and snippets.

@susodapop
Created November 7, 2021 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save susodapop/aa758e6dce83e7172d730abb9251b4b5 to your computer and use it in GitHub Desktop.
Save susodapop/aa758e6dce83e7172d730abb9251b4b5 to your computer and use it in GitHub Desktop.
"""
Author: Jesse Whitehouse
I used mkdocs to write static documentation for my Flask web application.
I write the docs in markdown and run `mkdocks build`, which outputs a full
static website into the /site directory.
In production, my webserver servers /site statically. But in development
mode I want to still see the docs for testing purposes. So I wrote this
View.
"""
from flask.views import MethodView
from flask import send_from_directory, redirect, url_for, request
def prepare_path(x):
"""Mirrors behavior of a typical webserver:
IN: css/main.css
OUT: css/main.css
IN articles/contributing/
OUT: articles/contributing/index.html
IN articles/contributing
OUT raise Exception
"""
if "." in x:
return x
if x[-1] == "/":
return x + "index.html"
raise Exception("Must redirect to include the trailing slash")
class TRMDocumentationView(MethodView):
# The path to your static files, relative
# to where your Flask app sits on disk
ROOT = "../docs/site"
def get(self, path):
try:
path = prepare_path(path)
return send_from_directory(self.ROOT, path)
except Exception:
return redirect(url_for(request.endpoint, path=path + "/"))
# TESTS
import pytest
VALID_URL = "changelog/index.html"
def test_trailing_slash():
assert prepare_path("changelog/") == VALID_URL
def test_css_assets():
assert prepare_path("css/theme.css") == "css/theme.css"
def test_js_assets():
assert prepare_path("js/modernizr-2.8.3.min.js") == "js/modernizr-2.8.3.min.js"
def test_no_trailing_slash():
with pytest.raises(Exception):
prepare_path("changelog")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment