summaryrefslogtreecommitdiff
path: root/repoze/bfg/router.py
blob: efc7406b622169d28f8b0b7ddecf3e267bc0a1e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from zope.component import getMultiAdapter
from zope.component import queryMultiAdapter
from zope.interface import directlyProvides

from webob import Request
from webob.exc import HTTPNotFound
from webob.exc import HTTPFound

from repoze.bfg.interfaces import IPublishTraverserFactory
from repoze.bfg.interfaces import IViewFactory
from repoze.bfg.interfaces import IWSGIApplicationFactory

from repoze.bfg.interfaces import IRequest

_marker = ()

class Router:
    def __init__(self, root_policy):
        self.root_policy = root_policy

    def __call__(self, environ, start_response):
        request = Request(environ)
        directlyProvides(request, IRequest)
        root = self.root_policy(environ)
        path = environ.get('PATH_INFO', '/')
        traverser = getMultiAdapter((root, request), IPublishTraverserFactory)
        context, name, subpath = traverser(path)
        if (not name) and (not path.endswith('/')):
            # if this is the default view of the context, and the URL
            # doesn't end in a slash, redirect to the url + '/' (so we
            # don't have to play base tag games)
            app = HTTPFound(add_slash=True)
        else:
            request.subpath = subpath
            app = queryMultiAdapter((context, request), IViewFactory, name=name,
                                    default=_marker)
            if app is _marker:
                app = HTTPNotFound(request.url)
            else:
                app = getMultiAdapter((app, request), IWSGIApplicationFactory)
        return app(environ, start_response)

def make_app(root_policy, package=None, filename='configure.zcml'):
    import zope.configuration.xmlconfig
    zope.configuration.xmlconfig.file(filename, package=package)
    return Router(root_policy)