From Bleach to JustHTML

Convert from Bleach to JustHTML (with Linkify!)

This rabbit hole inspired by this toot:

OK, #python , I’m updating an old project of mine and it uses bleach.
Bleach is now deprecated and unmaintained.
The most obvious solution is nh3 (https://nh3.readthedocs.io/en/latest/)
but it doesn’t have a “linkify” function.

Does anyone know of a solid alternative?

I hate to admit the AI that went into this. For one, JustHTML was openly written basically by an AI…

JustHTML is a fascinating example of vibe engineering in action

Then, I used the AI that came up with search results in Google (Gemini?) to help me figure out how to customize the allowed_tags list.

Sigh

But now it does exactly what I want and it doesn’t use deprecated/abandoned software. I’m using this on Stacks.


# utils.py

from justhtml import SanitizationPolicy, DEFAULT_POLICY


def extra_tlds():
    return {
        "app",
        "works",
        "press",
    }


def custom_policy_no_headings():
    headers = {"h1", "h2", "h3", "h4", "h5", "h6"}
    updated_allowed_tags = set(DEFAULT_POLICY.allowed_tags) - headers

    return SanitizationPolicy(
        allowed_tags=updated_allowed_tags,
        allowed_attributes=DEFAULT_POLICY.allowed_attributes,
        url_policy=DEFAULT_POLICY.url_policy,
    )


def custom_policy_no_tags():
    return SanitizationPolicy(
        allowed_tags={},
        allowed_attributes=DEFAULT_POLICY.allowed_attributes,
        url_policy=DEFAULT_POLICY.url_policy,
    )
# models.py

from markdown import markdown
from justhtml import JustHTML, Linkify
from .utils import extra_tlds, custom_policy_no_headings


class Example(models.Model):
    text = models.TextField(blank=True)

    @property
    def text_html(self):
        return JustHTML(
            markdown(
                self.text,
                extensions=[
                    "fenced_code",
                    "smarty",
                ],
            ),
            policy=custom_policy_no_headings(),
            transforms=[Linkify(extra_tlds=extra_tlds())],
            fragment=True,
        ).to_html()
<!-- template.html -->

{% if example.text_html %}
  <div class="content">
    {{ example.text_html|safe }}
  </div>
{% endif %}