Created
December 3, 2024 18:27
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
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
To make full use of this it expects the following:
index.md
in the current directory. this is the start pagetemplates
with a file calledbase.html
, this is your jinja2 template{{ content }}
marker anywhere so text knows where to render totext
, this is where you put all your files.have fun.