coding utf-8 import re from django conf import settings from django ht

 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
43
44
45
46
47
48
# -*- coding: utf-8 -*-
import re
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
class LocaleURLMiddleware(LocaleMiddleware):
def __init__(self):
self.supported = dict(settings.LANGUAGES)
self.url_check_re = re.compile(r'^/(?P<locale>%s)(?P<path>.*)$' % \
('|'.join(self.supported.keys())))
def remember_lang(self, request, lang):
if hasattr(request, 'session'):
request.session['django_language'] = lang
def process_request(self, request):
language = translation.get_language_from_request(request)[:2]
request.LANGUAGE_CODE = language
if not settings.USE_I18N:
return None
check = self.url_check_re.match(request.path_info)
if check:
url_lang = check.groupdict()['locale']
url_path = check.groupdict()['path']
if not url_path:
return HttpResponsePermanentRedirect('/%s/' % url_lang)
url_list = url_path.split('/')
request.path = request.path_info = request.META['PATH_INFO'] = u'/'.join(url_list)
self.remember_lang(request, url_lang)
translation.activate(url_lang)
request.LANGUAGE_CODE = url_lang
return None
if 'POST' in request.method:
translation.activate(language)
return None
redirect_url = None
for url in getattr(settings, 'NON_I18N_URLS', ()):
if not request.path_info.startswith(url):
redirect_url = u'/%s%s' % (language, request.path_info)
if redirect_url:
return HttpResponsePermanentRedirect(redirect_url)