__init__.py 1.83 KB
from pyramid.view import view_config
from pyramid.httpexceptions import (
    default_exceptionresponse_view,
    HTTPFound,
    )
from pyramid.interfaces import IRoutesMapper
from pyramid.response import Response
from pyramid.i18n import TranslationStringFactory


_ = TranslationStringFactory('home')


# http://stackoverflow.com/questions/9845669/pyramid-inverse-to-add-notfound-viewappend-slash-true
class RemoveSlashNotFoundViewFactory:
    def __init__(self, notfound_view=None):
        if notfound_view is None:
            notfound_view = default_exceptionresponse_view
        self.notfound_view = notfound_view

    def __call__(self, context, request):
        if not isinstance(context, Exception):
            # backwards compat for an append_notslash_view registered via
            # config.set_notfound_view instead of as a proper exception view
            context = getattr(request, 'exception', None) or context
        path = request.path
        registry = request.registry
        mapper = registry.queryUtility(IRoutesMapper)
        if mapper is not None and path.endswith('/'):
            noslash_path = path.rstrip('/')
            for route in mapper.get_routes():
                if route.match(noslash_path) is not None:
                    qs = request.query_string
                    if qs:
                        noslash_path += '?' + qs
                    return HTTPFound(location=noslash_path)
        return self.notfound_view(context, request)


@view_config(route_name='home', renderer='templates/home.pt')
def my_view(request):
    if '_LOCALE_' in request.GET:
        resp = Response()
        resp.set_cookie('_LOCALE_', request.GET['_LOCALE_'], 31536000)
        return HTTPFound(
            location=request.route_url('home'), headers=resp.headers)
    return dict(project='Web Instant Messaging Gateway', title=_('Home'))