src/p4l/utils.py
changeset 114 93b45b4f423c
parent 113 c05567404888
child 126 a345f1a67bf1
equal deleted inserted replaced
113:c05567404888 114:93b45b4f423c
     1 # -*- coding: utf-8 -*-
     1 # -*- coding: utf-8 -*-
     2 import codecs
     2 import codecs
     3 import logging
     3 import logging
     4 import math
     4 import math
       
     5 import hashlib
     5 import sys
     6 import sys
     6 import unicodedata
     7 import unicodedata
     7 
     8 
     8 from django.conf import settings
     9 from django.conf import settings
     9 from django.core.validators import URLValidator
    10 from django.core.validators import URLValidator
       
    11 from django.utils.http import urlquote_plus
    10 import requests
    12 import requests
    11 
    13 
    12 
    14 
    13 logger = logging.getLogger(__name__)
    15 logger = logging.getLogger(__name__)
    14 
    16 
   183 
   185 
   184 def strip_accents(value):
   186 def strip_accents(value):
   185     return ''.join(c for c in unicodedata.normalize('NFD', value)
   187     return ''.join(c for c in unicodedata.normalize('NFD', value)
   186                   if unicodedata.category(c) != 'Mn')
   188                   if unicodedata.category(c) != 'Mn')
   187     
   189     
       
   190     
       
   191 def safe_cache_key(value):
       
   192     '''Returns an md5 hexdigest of value if len(value) > 250. Replaces invalid memcache
       
   193        control characters with an underscore. Also adds the CACHE_MIDDLEWARE_KEY_PREFIX
       
   194        to your keys automatically.
       
   195     '''
       
   196     value = urlquote_plus(value)
       
   197     for char in value:
       
   198         if ord(char) < 33:
       
   199             value = value.replace(char, '_')
       
   200     
       
   201     value = "%s_%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, value)
       
   202     
       
   203     if len(value) <= 250:
       
   204         return value
       
   205     
       
   206     return hashlib.md5(value).hexdigest()
       
   207 
       
   208 
       
   209