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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
import re
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
from django.utils import translation
from django.utils.cache import patch_vary_headers
class LocaleURLMiddleware(object):
def get_language_from_request(self, request):
supported = dict(settings.LANGUAGES)
syslang = translation.get_language_from_request(request)[:2]
check = re.match(r'^/(%s)/?.*' % ('|'.join(supported.keys())), request.path)
changed = False
redir = False
if check is not None:
url_list = request.path.split('/')
if url_list.__len__() == 2:
url_list.append('')
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)
request.META['PATH_INFO'] = u'/'.join(url_list)
request.path_info = u'/'.join(url_list)
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:
redir = True
else:
if request.method == 'GET':
redir = True
if not changed:
if hasattr(request, 'session'):
lang = request.session.get('django_language', syslang)
if lang in supported and lang is not None:
return lang, redir
else:
lang = request.COOKIES.get('django_language', None)
if lang in supported and lang is not None:
return lang, redir
return lang, redir
def process_request(self, request):
language, redir = self.get_language_from_request(request)
if language is None:
language = settings.LANGUAGE_CODE[:2]
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
if redir and not request.path.startswith(settings.MEDIA_URL) and \
not request.path.startswith(settings.ADMIN_MEDIA_PREFIX):
redir_url = '/%s%s' % (language, request.path)
return HttpResponsePermanentRedirect(redir_url)
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response