lib/site.py
author Tero Marttila <terom@fixme.fi>
Sat, 07 Feb 2009 20:05:57 +0200
branchsites
changeset 36 02d4040d5946
parent 31 107062ebb6f9
permissions -rw-r--r--
start working on some nify URL parsing
"""
    Per-site stuff
"""

import imp

import handler

class Site (handler.RequestHandler) :
    """
        A site is a website and its configuration

        XXX: need to somehow communicate the site name to our downstream handler
    """

    def __init__ (self, name, handler) :
        """
            The given name must be like a valid hostname, e.g. 'www.qmsk.net'
        """

        # store
        self.name = name
        self.handler = handler

    def handle_request (self, request) :
        """
            Map the request through our handler...
        """

        return self.handler.handle_request(request)

class SiteModule (Site) :
    """
        A site, represented as python module/package, with the following module attributes:

            handler     - the RequestHandler to use
    """

    def __init__ (self, name, module) :
        """
            Create the Site based on the given module
        """

        super(SiteModule, self).__init__(name,
            module.handler
        )

class SiteModuleCollection (handler.RequestHandler) :
    """
        A collection of SiteModules, looking up the correct site to use based on the request hostname
    """

    def __init__ (self, path) :
        """
            Initialize to load site modules from the given path
        """

        self.path = path
        self.site_cache = dict()

    def handle_request (self, request) :
        """
            Lookup and return a Site object for the given request
        """

        # request hostnmae
        name = request.env['HTTP_HOST']
        
        # already loaded?
        if name in self.site_cache :
            site = self.site_cache[name]

        else :
            # first, we need to find it
            file, pathname, description = imp.find_module(name, [self.path])

            # then, we can load the module
            module = imp.load_module(name, file, pathname, description)
            
            # then build+cache the SiteModule
            site = self.site_cache[name] = SiteModule(name, module)

        # then execute the site's request handler
        return site.handle_request(request)