2
0

utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. from functools import wraps
  2. from django.core.cache import caches
  3. from django.core.validators import URLValidator
  4. from django.core.exceptions import ValidationError
  5. from django.middleware.cache import CacheMiddleware
  6. from django.utils.html import mark_safe
  7. from django.utils.translation import ugettext_lazy as _
  8. from wagtail.core import hooks
  9. from coderedcms.settings import cr_settings
  10. def get_protected_media_link(request, path, render_link=False):
  11. if render_link:
  12. return mark_safe("<a href='{0}{1}'>{0}{1}</a>".format(request.build_absolute_uri('/')[:-1], path))
  13. return "{0}{1}".format(request.build_absolute_uri('/')[:-1], path)
  14. def uri_validator(possible_uri):
  15. validate = URLValidator()
  16. try:
  17. validate(possible_uri)
  18. return True
  19. except ValidationError:
  20. return False
  21. def attempt_protected_media_value_conversion(request, value):
  22. new_value = value
  23. try:
  24. if value.startswith(cr_settings['PROTECTED_MEDIA_URL']):
  25. new_value = get_protected_media_link(request, value)
  26. except AttributeError:
  27. pass
  28. return new_value
  29. def clear_cache():
  30. if cr_settings['CACHE_PAGES']:
  31. cache = caches[cr_settings['CACHE_BACKEND']]
  32. cache.clear()
  33. def cache_page(view_func):
  34. """
  35. Decorator that determines whether or not to cache a page or serve a cached page.
  36. """
  37. @wraps(view_func)
  38. def _wrapped_view_func(request, *args, **kwargs):
  39. if cr_settings['CACHE_PAGES']:
  40. # check if request is cacheable
  41. request.is_preview = getattr(request, 'is_preview', False)
  42. is_cacheable = request.method in ('GET', 'HEAD') and not request.is_preview and not request.user.is_authenticated
  43. for fn in hooks.get_hooks('is_request_cacheable'):
  44. result = fn(request)
  45. if isinstance(result, bool):
  46. is_cacheable = result
  47. if is_cacheable:
  48. cache = caches[cr_settings['CACHE_BACKEND']]
  49. djcache = CacheMiddleware(
  50. cache_alias=cr_settings['CACHE_BACKEND'],
  51. cache_timeout=cache.default_timeout, # override CacheMiddleware's default timeout
  52. key_prefix=None
  53. )
  54. response = djcache.process_request(request)
  55. if response:
  56. response['X-Crcms-Cache'] = 'hit'
  57. return response
  58. # since we don't have a response at this point, run the view.
  59. response = view_func(request, *args, **kwargs)
  60. response['X-Crcms-Cache'] = 'miss'
  61. djcache.process_response(request, response)
  62. return response
  63. # as a fall-back, just run the view function.
  64. return view_func(request, *args, **kwargs)
  65. return _wrapped_view_func
  66. def seconds_to_readable(seconds):
  67. """
  68. Converts int seconds to a human readable string.
  69. """
  70. if seconds <= 0:
  71. return '{0} {1}'.format(str(seconds), _('seconds'))
  72. mins, secs = divmod(seconds, 60)
  73. hrs, mins = divmod(mins, 60)
  74. days, hrs = divmod(hrs, 24)
  75. pretty_time = ''
  76. if days > 0:
  77. pretty_time += ' {0} {1}'.format(str(days), _('days') if days > 1 else _('day'))
  78. if hrs > 0:
  79. pretty_time += ' {0} {1}'.format(str(hrs), _('hours') if hrs > 1 else _('hour'))
  80. if mins > 0:
  81. pretty_time += ' {0} {1}'.format(str(mins), _('minutes') if mins > 1 else _('minute'))
  82. if secs > 0:
  83. pretty_time += ' {0} {1}'.format(str(secs), _('seconds') if secs > 1 else _('second'))
  84. return pretty_time