svv/wsgi.py
author Tero Marttila <terom@fixme.fi>
Fri, 21 Jan 2011 04:44:30 +0200
changeset 61 ce1d012d02fe
parent 32 10c48a6843ad
permissions -rw-r--r--
html: amend
# coding: utf-8

"""
    WSGI frontend/entry point
"""

import werkzeug
from werkzeug import exceptions
from werkzeug import Request, Response

import logging            
import datetime

from svv import pdf
from svv import database as db
from svv.urls import URLS

# logging
log = logging.getLogger('svv.wsgi')

class WSGIApp (object) :
    """
        Top-level WSGI handler impl
    """

    def __init__ (self, app) :
        """
            app     - the top-level Application state used by handlers
        """
        
        self.app = app

    # wrap to use werkzeug's Request/Response
    @Request.application
    def __call__ (self, req) :
        """
            Main WSGI entry point, error handling
        """

        try :
            # wrapped handler
            response = self.request(req)

        except exceptions.HTTPException, e :
            # format properly as response, also includes redirects
            return e.get_response(req.environ)
        
        # XXX: except Exception, e :
        # XXX: we want to trap errors in prod, but not in dev?

        else :
            # a-ok
            return response

    def request (self, req) :
        """
            Wrapped request handler, URL mapping
        """

        # map URLs against this request
        urls = URLS.bind_to_environ(req)

        # lookup matching URL for handler type and matched values from URL
        url_handler, url_values = urls.match()

        # the per-request handler (from endpoint)
        req_handler = url_handler(self.app, req, urls)

        # XXX: per-method thing?
        response = req_handler.respond(**url_values)

        # ok
        return response