This repository has been archived by the owner on Aug 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.py
53 lines (48 loc) · 1.97 KB
/
middleware.py
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
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils import translation
from django.utils.html import strip_spaces_between_tags
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
class CompressHTML(object):
""" strip unsignificant whitespaces from response HTML"""
def process_response(self, request, response):
if response.status_code == 200 and not settings.DEBUG \
and 'text/html' in response['Content-Type']:
response.content = strip_spaces_between_tags(response.content)
response['Content-Length'] = str(len(response.content))
return response
class LangByTldMIddleware(object):
"""for multihost sites - set default lang by TLD"""
LANG_BY_TLD = {
'ae' : 'ar',
'cn' : 'zh-cn',
'hk' : 'zh-cn',
'tw' : 'zh-cn',
'th' : 'th',
'ru' : 'ru',
'ua' : 'ru',
'ca' : 'en',
'uk' : 'en',
'us' : 'en',
}
def __init__(self):
if not settings.USE_I18N:
raise MiddlewareNotUsed()
def process_request(self, request):
if not hasattr(request, 'LANGUAGE_CODE'):
raise ImproperlyConfigured(
'Please move LangByTldMIddleware below '
'django.middleware.LocaleMiddleware in your settings.py')
if hasattr(request, 'session') \
and 'django_language' in request.session \
or settings.LANGUAGE_COOKIE_NAME in request.COOKIES:
return None
if request.LANGUAGE_CODE not in \
request.META.get('HTTP_ACCEPT_LANGUAGE', ''):
domain = request.get_host()
tld = domain.split(':', 1)[0].rsplit('.', 1)[-1]
language = self.LANG_BY_TLD.get(tld, settings.LANGUAGE_CODE)
if language:
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
request.session['django_language'] = language