File: middleware.py

package info (click to toggle)
python-django-babel 0.6.2-7
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 264 kB
  • sloc: python: 662; makefile: 162
file content (42 lines) | stat: -rw-r--r-- 1,221 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# -*- coding: utf-8 -*-

from babel import Locale, UnknownLocaleError
from django.utils.translation import get_language
from threading import local

try:
    from django.utils.deprecation import MiddlewareMixin
except ImportError:
    # Not required for Django <= 1.9, see:
    # https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware
    MiddlewareMixin = object


__all__ = ['get_current_locale', 'LocaleMiddleware']

_thread_locals = local()


def get_current_locale():
    """Get current locale data outside views.

    See http://babel.pocoo.org/en/stable/api/core.html#babel.core.Locale
    for Locale objects documentation
    """
    return getattr(_thread_locals, 'locale', None)


class LocaleMiddleware(MiddlewareMixin):

    """Simple Django middleware that makes available a Babel `Locale` object
    via the `request.locale` attribute.
    """

    def process_request(self, request):
        try:
            code = getattr(request, 'LANGUAGE_CODE', get_language())
            locale = Locale.parse(code, sep='-')
        except (ValueError, UnknownLocaleError):
            pass
        else:
            _thread_locals.locale = request.locale = locale