[tor-commits] [bridgedb/master] Add function to HTML-encode strings

isis at torproject.org isis at torproject.org
Sat Jul 25 19:26:18 UTC 2015


commit faf4898324faaedf4ff675230e5275c264ab90b1
Author: Robert Ransom <rransom.8774 at gmail.com>
Date:   Thu Apr 30 05:17:42 2015 -0700

    Add function to HTML-encode strings
---
 lib/bridgedb/util.py |   20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/lib/bridgedb/util.py b/lib/bridgedb/util.py
index f3d87bd..8034120 100644
--- a/lib/bridgedb/util.py
+++ b/lib/bridgedb/util.py
@@ -180,6 +180,26 @@ def levenshteinDistance(s1, s2, len1=None, len2=None,
     memo[key] = distance
     return distance
 
+htmlify_string_map = {
+    '<': '<',
+    '>': '>',
+    '&': '&',
+    '"': '"',
+    "'": ''',
+    '\n': '<br/>'
+    }
+def htmlify_string(s):
+    """Encode HTML special characters, and newlines, in s.
+
+    >>> htmlify_string('<script>alert("badthink");</script>')
+    '<script>alert("badthink");</script>'
+    >>> htmlify_string('bridge 1\nbridge 2')
+    'bridge 1<br/>bridge 2'
+
+    :param str s: The string to encode.
+    """
+    return ''.join(map((lambda ch: htmlify_string_map.get(ch, ch)), s))
+
 
 class JustifiedLogFormatter(logging.Formatter):
     """A logging formatter which pretty prints thread and calling function





More information about the tor-commits mailing list