1. Fabio Michelini
  2. django-swingcms


django-swingcms / swingcms / cms / middleware.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.utils.cache import patch_vary_headers
from django.utils import translation
from django.http import Http404

import settings
from custodian.code import get_user
from swingexceptions import SwingException, MSG_GENERIC_ERROR, MSG_RESOURCE_DOES_NOT_EXIST
from cms.models import ds
from cms.views import message

class CommonMiddleware(object):

    def process_request(self, request):
        Choice url map depending of site status, redirecting to manutention or lock views.
        status = ds.SITE_STATUS
        if status == 'MANUTENTION' and not get_user(request).is_superuser:
            request.urlconf = 'cms.url_manutention'
        elif status == 'LOCK':
            request.urlconf = 'cms.url_lock'

    def process_exception(self, request, exception):
        Debug or manage and render exceptions in standarized message.
        Note that some errors raised in core handler bypass middlewares:
        those are interceptable with 404 and 500 errors handler defined in
        urls and redirecting to standard message view.
        if settings.DEBUG:
            return None

        if isinstance(exception, SwingException):
            # intercept all standart exceptions (either subclass), optionally display message
            msg, level, display = exception.args
            msg = display and msg or MSG_GENERIC_ERROR
        elif isinstance(exception, Http404):
            # 404: intercept exception raised from get_obj_or_404
            msg, level = MSG_RESOURCE_DOES_NOT_EXIST, 'ERROR'
            # 500: intercept generic internal exception, hide message and default level
            msg, level = MSG_GENERIC_ERROR, 'ERROR'

        return message(request, msg, level)

class LocaleMiddleware(object):
    Little hack around ack canonical language choice of django: depending of settings,
    bypass or not the client language preferences.
    def process_request(self, request):

        if not settings.EVALUATE_CLIENT_LANGUAGE_PREFERENCE and 'django_language' not in request.session:
            language = settings.LANGUAGE_CODE
            request.session.setdefault('django_language', language)
            language = translation.get_language_from_request(request)
        request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):

        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        return response