X-Git-Url: https://git.mdrn.pl/fnpdjango.git/blobdiff_plain/7b2a81536977bb13b68ada3e5a281e35b24e0bfd..610dacb44133c2efc65faa379a97eeda64d3581b:/fnpdjango/middleware.py?ds=inline diff --git a/fnpdjango/middleware.py b/fnpdjango/middleware.py index 21de872..734e878 100644 --- a/fnpdjango/middleware.py +++ b/fnpdjango/middleware.py @@ -1,31 +1,53 @@ -from django.utils import translation -from django.conf import settings -from django.http import Http404 +from . import app_settings +try: + # Django >= 1.10 + from django.utils.deprecation import MiddlewareMixin +except ImportError: + # Django <= 1.9 + MiddlewareMixin = object -class SetRemoteAddrFromXRealIP(object): - """Sets REMOTE_ADDR from the X-Real-IP header, as set by Nginx.""" - def process_request(self, request): - try: - request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP'] - except KeyError: - return None + from django.conf import settings + from django.http import Http404 + from django.utils import translation + class URLLocaleMiddleware(MiddlewareMixin): + """Decides which translation to use, based on path only.""" + def process_request(self, request): + language = translation.get_language_from_path(request.path_info) + if language: + translation.activate(language) + request.LANGUAGE_CODE = translation.get_language() + if language == settings.LANGUAGE_CODE: + raise Http404 -class URLLocaleMiddleware(object): - """Decides which translation to use, based on path only.""" + def process_response(self, request, response): + language = translation.get_language() + translation.deactivate() + if 'Content-Language' not in response: + response['Content-Language'] = language + return response +else: + # Django >= 1.10 + import warnings + from django.middleware.locale import LocaleMiddleware - def process_request(self, request): - language = translation.get_language_from_path(request.path_info) - if language == settings.LANGUAGE_CODE: - raise Http404 - if language: - translation.activate(language) - request.LANGUAGE_CODE = translation.get_language() + class URLLocaleMiddleware(LocaleMiddleware): + def __init__(self, *args, **kwargs): + warnings.warn( + "As of Django 1.10, fnpdjango.middleware.URLLocaleMiddleware " + "is deprecated in favor of " + "django.middleware.locale.LocaleMiddleware.", + DeprecationWarning) + super(URLLocaleMiddleware, self).__init__(*args, **kwargs) - def process_response(self, request, response): - language = translation.get_language() - translation.deactivate() - if 'Content-Language' not in response: - response['Content-Language'] = language - return response + +class SetRemoteAddrFromXRealIP(MiddlewareMixin): + """Sets REMOTE_ADDR from the X-Real-IP header, as set by Nginx.""" + def process_request(self, request): + if app_settings.REALIP: + try: + request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP'] + except KeyError: + pass + return None