summaryrefslogtreecommitdiff
path: root/django/utils
diff options
context:
space:
mode:
authorClaude Paroz <claude@2xlibre.net>2014-03-20 16:50:50 +0100
committerClaude Paroz <claude@2xlibre.net>2014-03-22 11:01:14 +0100
commit80f08dbdbc1f9c8b4ed75298955016feb697c4a1 (patch)
treedda3a74763844deb41fdf180db074d8b64d27249 /django/utils
parent0c19383a1ffaaefe92b7b3bfaac6885525afd9a9 (diff)
[1.7.x] Improved strip_tags and clarified documentation
The fact that strip_tags cannot guarantee to really strip all non-safe HTML content was not clear enough. Also see: https://www.djangoproject.com/weblog/2014/mar/22/strip-tags-advisory/ Backport of 6ca6c36f82b from master.
Diffstat (limited to 'django/utils')
-rw-r--r--django/utils/html.py31
1 files changed, 27 insertions, 4 deletions
diff --git a/django/utils/html.py b/django/utils/html.py
index 6afd6b62fa..db2a21a4dc 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -120,7 +120,10 @@ linebreaks = allow_lazy(linebreaks, six.text_type)
class MLStripper(HTMLParser):
def __init__(self):
- HTMLParser.__init__(self)
+ if six.PY2:
+ HTMLParser.__init__(self)
+ else:
+ HTMLParser.__init__(self, strict=False)
self.reset()
self.fed = []
@@ -137,16 +140,36 @@ class MLStripper(HTMLParser):
return ''.join(self.fed)
-def strip_tags(value):
- """Returns the given HTML with all tags stripped."""
+def _strip_once(value):
+ """
+ Internal tag stripping utility used by strip_tags.
+ """
s = MLStripper()
try:
s.feed(value)
- s.close()
except HTMLParseError:
return value
+ try:
+ s.close()
+ except (HTMLParseError, UnboundLocalError) as err:
+ # UnboundLocalError because of http://bugs.python.org/issue17802
+ # on Python 3.2, triggered by strict=False mode of HTMLParser
+ return s.get_data() + s.rawdata
else:
return s.get_data()
+
+
+def strip_tags(value):
+ """Returns the given HTML with all tags stripped."""
+ while True:
+ if not ('<' in value or '>' in value):
+ return value
+ new_value = _strip_once(value)
+ if new_value == value:
+ # _strip_once was not able to detect more tags
+ return value
+ else:
+ value = new_value
strip_tags = allow_lazy(strip_tags)