Martin von Löwis committed a7cfbeb

Port sanitize to 3k.

  • Participants
  • Parent commits 20c3597

Comments (0)

Files changed (1)


 against request forgeries from other sites.
+import sys
 import itertools
 import re
 import random
 from django.utils.cache import patch_vary_headers
 from django.utils.hashcompat import md5_constructor
 from django.utils.safestring import mark_safe
+from django.utils.py3 import b
     re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
 def _sanitize_token(token):
     # Allow only alphanum, and ensure we return a 'str' for the sake of the post
     # processing middleware.
-    token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
+    if isinstance(token, unicode):
+        token = token.encode('ascii', 'ignore')
+    token = re.sub(b('[^a-zA-Z0-9]'), b(''), token)
     if token == "":
         # In case the cookie has been truncated to nothing at some point.
         return _get_new_csrf_key()
-        return token
+        if sys.version_info < (3,):
+            return token
+        else:
+            return token.decode('ascii')
 class CsrfViewMiddleware(object):