Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Use unicode.translate to speed up js escaping.

  • Loading branch information...
commit 44767f2caf028d89e1a283d04bb552d0e18bb936 1 parent 40e62a5
Dave Hall authored September 18, 2012 apollo13 committed September 18, 2012

Showing 1 changed file with 15 additions and 18 deletions. Show diff stats Hide diff stats

  1. 33  django/utils/html.py
33  django/utils/html.py
@@ -42,29 +42,26 @@ def escape(text):
42 42
     return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
43 43
 escape = allow_lazy(escape, six.text_type)
44 44
 
45  
-_base_js_escapes = (
46  
-    ('\\', '\\u005C'),
47  
-    ('\'', '\\u0027'),
48  
-    ('"', '\\u0022'),
49  
-    ('>', '\\u003E'),
50  
-    ('<', '\\u003C'),
51  
-    ('&', '\\u0026'),
52  
-    ('=', '\\u003D'),
53  
-    ('-', '\\u002D'),
54  
-    (';', '\\u003B'),
55  
-    ('\u2028', '\\u2028'),
56  
-    ('\u2029', '\\u2029')
57  
-)
  45
+_js_escapes = {
  46
+    ord('\\'): '\\u005C',
  47
+    ord('\''): '\\u0027',
  48
+    ord('"'): '\\u0022',
  49
+    ord('>'): '\\u003E',
  50
+    ord('<'): '\\u003C',
  51
+    ord('&'): '\\u0026',
  52
+    ord('='): '\\u003D',
  53
+    ord('-'): '\\u002D',
  54
+    ord(';'): '\\u003B',
  55
+    ord('\u2028'): '\\u2028',
  56
+    ord('\u2029'): '\\u2029'
  57
+}
58 58
 
59 59
 # Escape every ASCII character with a value less than 32.
60  
-_js_escapes = (_base_js_escapes +
61  
-               tuple([('%c' % z, '\\u%04X' % z) for z in range(32)]))
  60
+_js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
62 61
 
63 62
 def escapejs(value):
64 63
     """Hex encodes characters for use in JavaScript strings."""
65  
-    for bad, good in _js_escapes:
66  
-        value = mark_safe(force_text(value).replace(bad, good))
67  
-    return value
  64
+    return mark_safe(force_text(value).translate(_js_escapes))
68 65
 escapejs = allow_lazy(escapejs, six.text_type)
69 66
 
70 67
 def conditional_escape(text):

0 notes on commit 44767f2

Please sign in to comment.
Something went wrong with that request. Please try again.