util.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. import json
  5. import sys
  6. from django.conf import settings
  7. from django.core.exceptions import ImproperlyConfigured
  8. from django.utils.functional import Promise
  9. from django.utils.six.moves.urllib.parse import urlparse
  10. try:
  11. from django.utils.encoding import force_unicode as force_text
  12. except ImportError:
  13. from django.utils.encoding import force_text # Python 3
  14. class LazyEncoder(json.JSONEncoder):
  15. """
  16. JSONEncoder that turns Promises into unicode strings to support functions
  17. like ugettext_lazy and reverse_lazy.
  18. """
  19. def default(self, obj):
  20. if isinstance(obj, Promise):
  21. return force_text(obj)
  22. return super(LazyEncoder, self).default(obj)
  23. def import_from_setting(setting):
  24. """
  25. Attempt to load a module attribute from a module as specified by a setting.
  26. :raises:
  27. ImproperlyConfigured if anything goes wrong.
  28. """
  29. try:
  30. path = getattr(settings, setting)
  31. except AttributeError as e:
  32. raise ImproperlyConfigured('Setting {0} not found.'.format(setting))
  33. try:
  34. i = path.rfind('.')
  35. module, attr = path[:i], path[i + 1:]
  36. except AttributeError as e:
  37. raise ImproperlyConfigured('Setting {0} should be an import path.'.format(setting))
  38. try:
  39. __import__(module)
  40. mod = sys.modules[module]
  41. except ImportError as e:
  42. raise ImproperlyConfigured('Error importing `{0}`: {1}'.format(path, e))
  43. try:
  44. return getattr(mod, attr)
  45. except AttributeError as e:
  46. raise ImproperlyConfigured('Module {0} does not define `{1}`.'.format(module, attr))
  47. def same_origin(url1, url2):
  48. """
  49. Checks if two URLs share the same origin, IE the same protocol,
  50. host, and port.
  51. """
  52. p1, p2 = urlparse(url1), urlparse(url2)
  53. return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)