import re from django conf import settings from django http import Htt

 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
49
50
51
52
53
54
55
56
57
58
59
60
import re
from django.conf import settings
from django.http import Http404, HttpResponsePermanentRedirect
from django.utils import translation
from django.utils.cache import patch_vary_headers
class RedirectLanguage(Exception):
pass
class LocaleURLMiddleware:
def get_language_from_request(self, request):
supported = dict(settings.LANGUAGES)
lang = settings.LANGUAGE_CODE[:2]
check = re.match(r"^/(\w\w)/.*", request.path)
changed = False
if check is not None:
print 'Found lang'
url_list = request.path.split('/')
t = check.group(1)
if t in url_list and url_list.index(t) == 1:
del url_list[1]
request.path = u'/'.join(url_list)
print request.path
if t in supported:
lang = t
if hasattr(request, 'session'):
request.session['django_language'] = lang
else:
response.set_cookie('django_language', lang)
changed = True
else:
raise RedirectLanguage
if not changed:
if hasattr(request, 'session'):
lang = request.session.get('django_language', None)
if lang in supported and lang is not None:
return lang
else:
lang = request.COOKIES.get('django_language', None)
if lang in supported and lang is not None:
return lang
return lang
def process_request(self, request):
language = self.get_language_from_request(request)
if language is None:
language = settings.LANGUAGE_CODE[:2]
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
translation.deactivate()
return response
def process_exception(self, request, exception):
if isinstance(exception,RedirectLanguage):
redir_url = '/%s%s' % (request.LANGUAGE_CODE, request.path)
print 'lang not found in url, redirecting to %s' % redir_url
return HttpResponsePermanentRedirect(redir_url)