Login

BabelMiddleware

Author:
skam
Posted:
July 16, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

Originally posted on skam.webfactional.com

This is a very simple middleware that uses babel (http://babel.edgewall.org) for accessing locale data in request objects through request.LOCALE attribute.

It also provides a function to get locale data outside views.

settings.py:

MIDDLEWARE_CLASSES = (
    ... cut ...
    'django.middleware.locale.LocaleMiddleware',
    'middleware.locale.BabelMiddleware',
    ... cut ...
)
 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
import babel

try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_locale():
    """
    Get current locale data outside views.
    See http://babel.edgewall.org/wiki/ApiDocs/babel.core for Locale
    objects documentation
    """
    return getattr(_thread_locals, 'locale', None)

class BabelMiddleware(object):
    """
    This is a simple middleware that uses
    babel (http://babel.edgewall.org) for accessing locale
    data in request objects through request.LOCALE attribute
    """
    def process_request(self, request):
        try:
            locale = babel.Locale.parse(request.LANGUAGE_CODE, sep='-')
        except (ValueError, babel.UnknownLocaleError):
            pass
        else:
            _thread_locals.locale = locale
            setattr(request, 'LOCALE', locale)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.