Skip to content

Instantly share code, notes, and snippets.

@Kraballa
Created December 3, 2024 18:27
Show Gist options
  • Save Kraballa/8ce6dea5341793e2be54623cf3db7326 to your computer and use it in GitHub Desktop.
Save Kraballa/8ce6dea5341793e2be54623cf3db7326 to your computer and use it in GitHub Desktop.
Fully featured commonmark markdown rendering python flask server. Supports links, images and some extensions.
from flask import Flask, request, render_template, make_response, send_file
from markupsafe import Markup
from markdown_it import MarkdownIt
from mdit_py_plugins.footnote import footnote_plugin
from mdit_py_plugins.tasklists import tasklists_plugin
from mdit_py_plugins.front_matter import front_matter_plugin # parses header info
from mdit_py_plugins.texmath import texmath_plugin
import os
md = (
MarkdownIt('commonmark', {'breaks':True, 'html':True})
.enable('table')
.enable('strikethrough')
.use(footnote_plugin)
.use(front_matter_plugin)
.use(texmath_plugin)
)
tasklists_plugin(md, enabled=True) # need to enable checkboxes so we can style them on chrome
app = Flask(__name__)
not_found = Markup(md.render("<h3>file not found</h3><p>the file couldn't be found</p>"))
@app.get("/")
@app.get("/index.md")
@app.get("/index.html")
def index():
text = readFile("index.md")
return render_template("base.html", content=text)
@app.get("/<path:subpath>")
def read(subpath=""):
subpath = "./text/" + subpath
if subpath.endswith(".md"):
if os.path.exists(subpath):
text = readFile(subpath)
else:
text = not_found
else:
if os.path.exists(subpath):
return send_file(subpath)
else:
return make_response("file not found", 404)
return render_template("base.html", content=text)
def readFile(path):
print("reading file", path)
with open(path, "r", encoding="utf-8") as file:
text = file.read()
return Markup(md.render(text))
@Kraballa
Copy link
Author

Kraballa commented Dec 3, 2024

To make full use of this it expects the following:

  • a file called index.md in the current directory. this is the start page
  • a folder called templates with a file called base.html, this is your jinja2 template
    • place atleast the {{ content }} marker anywhere so text knows where to render to
  • a folder called text, this is where you put all your files.

have fun.

@Kraballa
Copy link
Author

Kraballa commented Dec 3, 2024

you can start a simple debug server with python -m flask --app server run --debug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment