middleware.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2007 Edgewall Software
  4. # All rights reserved.
  5. #
  6. # This software is licensed as described in the file COPYING, which
  7. # you should have received as part of this distribution. The terms
  8. # are also available at http://babel.edgewall.org/wiki/License.
  9. #
  10. # This software consists of voluntary contributions made by many
  11. # individuals. For the exact contribution history, see the revision
  12. # history and logs, available at http://babel.edgewall.org/log/.
  13. from babel import Locale, UnknownLocaleError
  14. from django.conf import settings
  15. try:
  16. from threading import local
  17. except ImportError:
  18. from django.utils._threading_local import local
  19. __all__ = ['get_current_locale', 'LocaleMiddleware']
  20. _thread_locals = local()
  21. def get_current_locale():
  22. """Get current locale data outside views.
  23. See http://babel.edgewall.org/wiki/ApiDocs/babel.core for Locale
  24. objects documentation
  25. """
  26. return getattr(_thread_locals, 'locale', None)
  27. class LocaleMiddleware(object):
  28. """Simple Django middleware that makes available a Babel `Locale` object
  29. via the `request.locale` attribute.
  30. """
  31. def process_request(self, request):
  32. try:
  33. code = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
  34. locale = Locale.parse(code, sep='-')
  35. except (ValueError, UnknownLocaleError):
  36. pass
  37. else:
  38. _thread_locals.locale = request.locale = locale