lib/map.py
author Tero Marttila <terom@fixme.fi>
Sat, 07 Feb 2009 16:33:27 +0200
branchsites
changeset 31 107062ebb6f9
parent 30 a86a25a9f75b
child 32 be954df4f0e8
permissions -rw-r--r--
bloat code with even more layers of indirection, split off the filesystem-based stuff into a separate lib.filesystem package (next, move it to sites/www.qmsk.net)
"""
    Handles mapping URLs to request handlers
"""

import http
import handler

class MappingError (http.ResponseError) :
    """
        URL could not be mapped
    """

    def __init__ (self, url) :
        super(MappingError, self).__init__("URL not found: %s" % (url, ), status='404 Not Found')

class Mapper (handler.RequestHandler) :
    """
        Looks up the handler to use based on the URL
    """

    def handle_request (self, request) :
        """
            Map the given request
        """

        abstract

class Mapping (object) :
    """
        A mapping object for StaticMapping
    """

    def test (self, request) :
        """
            Either return a handler, or None
        """

        abstract

class RegexpMapping (object) :
    """
        A mapping object that uses regular expressions
    """

    def __init__ (self, regexp, handler) :
        pass

    def test (self, request) :
        xxx

class SimpleMapping (object) :
    """
        A mapping object that uses simple expressions
    """

    def __init__ (self, expression, handler) :
        pass

    def test (self, request) :
        xxx

class StaticMapping (Mapper) :
    """
        Translates requests to handlers using a list of pre-determined Mapping's
    """

    def __init__ (self, mappings) :
        # store
        self.mappings = mappings

    def map_request (self, request) :
        """
            Returns the appropriate handler
        """

        # find handler to use
        handler = None

        # just test each mapping in turn
        for mapping in self.mappings :
            handler = mapping.test(request)

            if handler :
                break
        
        if not handler :
            # fail, not found
            raise MappingError(request.get_page_name())
        
        # passthrough
        return handler.handle_request(request)

# "friendly" names
map     = SimpleMapping
mapre   = RegexpMapping