21de87258e71c3bd76b542b48974d45c8ea1a4ab
[fnpdjango.git] / fnpdjango / middleware.py
1 from django.utils import translation
2 from django.conf import settings
3 from django.http import Http404
4
5
6 class SetRemoteAddrFromXRealIP(object):
7     """Sets REMOTE_ADDR from the X-Real-IP header, as set by Nginx."""
8     def process_request(self, request):
9         try:
10             request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP']
11         except KeyError:
12             return None
13
14
15 class URLLocaleMiddleware(object):
16     """Decides which translation to use, based on path only."""
17
18     def process_request(self, request):
19         language = translation.get_language_from_path(request.path_info)
20         if language == settings.LANGUAGE_CODE:
21             raise Http404
22         if language:
23             translation.activate(language)
24         request.LANGUAGE_CODE = translation.get_language()
25
26     def process_response(self, request, response):
27         language = translation.get_language()
28         translation.deactivate()
29         if 'Content-Language' not in response:
30             response['Content-Language'] = language
31         return response