1 | from django.utils.cache import patch_vary_headers
|
---|
2 | from django.utils import translation
|
---|
3 | from blog import settings
|
---|
4 |
|
---|
5 | class LocaleURLMiddleware:
|
---|
6 | def get_language_from_request (self,request):
|
---|
7 | from django.conf import settings
|
---|
8 | import re
|
---|
9 | supported = dict(settings.LANGUAGES)
|
---|
10 | lang = settings.LANGUAGE_CODE[:2]
|
---|
11 | check = re.match(r'/(\w\w)/.*', request.path)
|
---|
12 | changed = False
|
---|
13 | if check is not None:
|
---|
14 | t = check.group(1)
|
---|
15 | if t in supported:
|
---|
16 | lang = t
|
---|
17 | if hasattr(request, 'session'):
|
---|
18 | request.session['django_language'] = lang
|
---|
19 | else:
|
---|
20 | response.set_cookie('django_language', lang)
|
---|
21 | changed = True
|
---|
22 | if not changed:
|
---|
23 | if hasattr(request, 'session'):
|
---|
24 | lang = request.session.get('django_language', None)
|
---|
25 | if lang in supported and lang is not None:
|
---|
26 | return lang
|
---|
27 | else:
|
---|
28 | lang = request.COOKIES.get('django_language', None)
|
---|
29 | if lang in supported and lang is not None:
|
---|
30 | return lang
|
---|
31 | return lang
|
---|
32 | def process_request(self, request):
|
---|
33 | from django.conf import settings
|
---|
34 | language = self.get_language_from_request(request)
|
---|
35 | if language is None:
|
---|
36 | language = settings.LANGUAGE_CODE[:2]
|
---|
37 | translation.activate(language)
|
---|
38 | request.LANGUAGE_CODE = translation.get_language()
|
---|
39 | def process_response(self, request, response):
|
---|
40 | patch_vary_headers(response, ('Accept-Language',))
|
---|
41 | translation.deactivate()
|
---|
42 | return response
|
---|
43 |
|
---|
44 | def get_absolute_path_without_lang(request):
|
---|
45 | for lang in settings.LANGUAGES:
|
---|
46 | if '' + str(lang[0]) + '' in request.path:
|
---|
47 | return request.path.replace('/' + str(lang[0]) + '', '')
|
---|
48 | return request.path
|
---|