From 9e505bc638e0eb7d40f0ce18afdfeb1077a98075 Mon Sep 17 00:00:00 2001 From: ubq323 Date: Mon, 14 Jun 2021 14:33:36 +0000 Subject: improve markdown rendering and html saniti(s/z)ation; enable strikethrough with tildes --- apioforum/mdrender.py | 23 +++++++++++++++++++++++ apioforum/thread.py | 8 ++------ setup.py | 2 ++ 3 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 apioforum/mdrender.py diff --git a/apioforum/mdrender.py b/apioforum/mdrender.py new file mode 100644 index 0000000..20e86bb --- /dev/null +++ b/apioforum/mdrender.py @@ -0,0 +1,23 @@ +import bleach + +allowed_tags = [ + 'p', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'pre', + 'del', +] +allowed_tags.extend(bleach.sanitizer.ALLOWED_TAGS) + +cleaner = bleach.sanitizer.Cleaner(tags=allowed_tags) + +import markdown +md = markdown.Markdown(extensions=['pymdownx.tilde']) + +def render(text): + text = md.reset().convert(text) + text = cleaner.clean(text) + return text diff --git a/apioforum/thread.py b/apioforum/thread.py index b9697ce..3378982 100644 --- a/apioforum/thread.py +++ b/apioforum/thread.py @@ -5,11 +5,7 @@ from flask import ( url_for, flash ) from .db import get_db - -def render_md(md): - from markdown import markdown - from markupsafe import escape - return markdown(escape(md)) +from .mdrender import render bp = Blueprint("thread", __name__, url_prefix="/thread") @@ -24,7 +20,7 @@ def view_thread(thread_id): "SELECT * FROM posts WHERE thread = ? ORDER BY created ASC;", (thread_id,) ).fetchall() - rendered_posts = [render_md(q['content']) for q in posts] + rendered_posts = [render(q['content']) for q in posts] return render_template("view_thread.html",posts=posts,thread=thread,thread_id=thread_id,rendered_posts=rendered_posts) @bp.route("//create_post", methods=("POST",)) diff --git a/setup.py b/setup.py index 9282914..089f3a4 100644 --- a/setup.py +++ b/setup.py @@ -8,5 +8,7 @@ setup( install_requires = [ 'flask', 'markdown', + 'bleach', + 'pymdown-extensions', ], ) -- cgit v1.2.3