Source

flickzeug / flickzeug / utils / __init__.py

Full commit
# -*- coding: utf-8 -*-
"""
    flickzeug.utils
    ~~~~~~~~~~~~~~~

    Various other utilities.

    :copyright: (c) 2009 by the Flickzeug Team, see AUTHORS for more details.
    :license: BSD.
"""
from os import stat
from os.path import join, dirname, sep
from werkzeug import SharedDataMiddleware
from werkzeug.exceptions import NotFound, HTTPException
from werkzeug.templates import Template
from werkzeug.wrappers import Response, Request
from werkzeug.routing import Map, Rule, Submount

import flickzeug

LOADED_TEMPLATES_CACHE = {}

def get_template(filename):
    template_path = join(dirname(flickzeug.__file__), 'templates',
                         sep.join(filename.split('/')))
    if template_path in LOADED_TEMPLATES_CACHE:
        template, mod_time = LOADED_TEMPLATES_CACHE[template_path]
        if mod_time == stat(template_path).st_mtime:
            return template
    template = Template.from_file(template_path)
    mod_time = stat(template_path).st_mtime
    LOADED_TEMPLATES_CACHE[template_path] = (template, mod_time)
    return template

def render_template(template_filename, **context):
    return get_template(template_filename).render(**context)

def render_response(template_filename, **context):
    return Response(render_template(template_filename, **context),
                    mimetype='text/html')


class WebMiddleware(object):

    def __init__(self, app, app_path):
        self.app = app
        self.app_path = app_path

        self.dispatch_wsgi = SharedDataMiddleware(self.dispatch_wsgi, {
            '/'.join([app_path, 'shared']):
                join(dirname(flickzeug.__file__), 'shared')
        })

        self.url_map = Map([Submount(
            app_path,
            self.get_url_rules() + [Rule('/shared/<filename>',
                                         build_only=True, endpoint='shared')]
            )
        ])

    def get_url_rules(self):
        raise NotImplementedError("You need to override the 'get_url_rules()' "
                                  "function on your class and return the "
                                  "necessary url rules for your middleware.")

    def url_for(self, endpoint, **args):
        return self.url_adapter.build(endpoint, args)

    def subdispatch_wsgi(self, environ, start_response):
        return self.app(environ, start_response)

    def dispatch_wsgi(self, environ, start_response):
        req = Request(environ)
        self.url_adapter = self.url_map.bind_to_environ(environ)
        try:
            endpoint, args = self.url_adapter.match()
            return self.handlers[endpoint](req, **args)(environ, start_response)
        except KeyError:
            return Response('Not Found', status=404)(environ, start_response)
        except NotFound:
            if req.path.startswith(self.app_path):
                return Response('Not Found', status=404)(environ,
                                                         start_response)
            return self.subdispatch_wsgi(environ, start_response)
        except HTTPException, err:
            return err.get_response(req)(environ, start_response)

    def __call__(self, environ, start_response):
        return self.dispatch_wsgi(environ, start_response)