lib/map.py
author Tero Marttila <terom@fixme.fi>
Sat, 07 Feb 2009 06:54:52 +0200
branchsites
changeset 30 a86a25a9f75b
child 31 107062ebb6f9
permissions -rw-r--r--
route requests through sites/www.qmsk.net, although still hardcoded
"""
    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 (object) :
    """
        Translates requests to handlers
    """

    def map_request (self, request) :
        """
            Map the given request, returning a Handler
        """

        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
        """

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

            if handler :
                return handler
        
        # fail, not found
        raise MappingError(request.get_page_name())
        
class FilesystemMapper (Mapper) :
    """
        Translates requests to handlers based on a filesystem directory containing various kinds of files
    """

    def __init__ (self, path) :
        """
            Create, path is where the pages are stored
        """
        
        # store
        self.path = path
    
    def map_request (self, request) :
        """
            Looks up the appropriate Page, and then returns a generic Handler
        """

        # XXX: harcoded
        return handler.Handler(handler.handle_request)

# "friendly" names
fstree  = FilesystemMapper

map     = SimpleMapping
mapre   = RegexpMapping