734e878a1340c4aa0837b0c5537f2eb36febd5fe
[fnpdjango.git] / fnpdjango / middleware.py
1 from . import app_settings
2
3 try:
4     # Django >= 1.10
5     from django.utils.deprecation import MiddlewareMixin
6 except ImportError:
7     # Django <= 1.9
8     MiddlewareMixin = object
9
10     from django.conf import settings
11     from django.http import Http404
12     from django.utils import translation
13
14     class URLLocaleMiddleware(MiddlewareMixin):
15         """Decides which translation to use, based on path only."""
16         def process_request(self, request):
17             language = translation.get_language_from_path(request.path_info)
18             if language:
19                 translation.activate(language)
20             request.LANGUAGE_CODE = translation.get_language()
21             if language == settings.LANGUAGE_CODE:
22                 raise Http404
23
24         def process_response(self, request, response):
25             language = translation.get_language()
26             translation.deactivate()
27             if 'Content-Language' not in response:
28                 response['Content-Language'] = language
29             return response
30 else:
31     # Django >= 1.10
32     import warnings
33     from django.middleware.locale import LocaleMiddleware
34
35     class URLLocaleMiddleware(LocaleMiddleware):
36         def __init__(self, *args, **kwargs):
37             warnings.warn(
38                 "As of Django 1.10, fnpdjango.middleware.URLLocaleMiddleware "
39                 "is deprecated in favor of "
40                 "django.middleware.locale.LocaleMiddleware.",
41                 DeprecationWarning)
42             super(URLLocaleMiddleware, self).__init__(*args, **kwargs)
43
44
45 class SetRemoteAddrFromXRealIP(MiddlewareMixin):
46     """Sets REMOTE_ADDR from the X-Real-IP header, as set by Nginx."""
47     def process_request(self, request):
48         if app_settings.REALIP:
49             try:
50                 request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP']
51             except KeyError:
52                 pass
53         return None