Safely formatting HTML text in python (ala textile)

I was looking for an existing textile-style python library to format text for user login.

If I just went into it, it would just be great to work with textiles, but since the input is for a django application that will accept user input and display it, while preserving some formatting.

I managed to find small loopholes here in the existing libraries that I saw. They sometimes don’t avoid things as they should, would allow me to enter direct HTML and the list goes on.

So, what are some guidelines on conversion mechanisms that I can use?

+3
source share
3 answers

If you use Django, you can try a safe markdown:

{% load markup %}

{{ foo|markdown:"safe" }}

You need to set a markdown django.contrib.markupin your applications settings.py.

If you want to sanitize the HTML for saving, I was fortunate enough to use the feedparser bathroom ( http://www.feedparser.org/ ).

import feedparser

body = feedparser._sanitizeHTML(body, 'utf8')
+6
source

: PyTextile, django, textile_restricted(), - django.contrib.markup. . , text_restricted, textile_restricted, :

from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe

register = template.Library()

def textile_restricted(value):
    try:
        import textile
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.")
        return force_unicode(value)
    else:
        return mark_safe(force_unicode(textile.textile_restricted(smart_str(value))))
textile_restricted.is_safe = True

register.filter(textile_restricted)
+2

Have you tried the included django.contrib.markup libraries ?

+1
source

Source: https://habr.com/ru/post/1722369/


All Articles