Source

lodgeit-main / lodgeit / wsgi / application.py

Full commit
# -*- coding: utf-8 -*-
"""
    lodgeit.application
    ~~~~~~~~~~~~~~~~~~~

    the WSGI application

    :copyright: 2007-2009 by Armin Ronacher, Christopher Grebs.
    :license: BSD
"""
import os
from datetime import datetime, timedelta
import logging

from werkzeug import SharedDataMiddleware, ClosingIterator
from werkzeug.exceptions import HTTPException, NotFound

from lodgeit import i18n, config
from lodgeit.controllers import get_controller
from lodgeit.database import db
from lodgeit.models import Paste
from lodgeit.search import build_indexer
from lodgeit.wsgi.local import ctx, local_manager
from lodgeit.wsgi.urls import urlmap
from lodgeit.wsgi.utils import COOKIE_NAME, Request, jinja_environment

log = logging.getLogger(__name__)


class LodgeIt(object):
    """The WSGI Application"""

    def __init__(self):
        self.secret_key = config.get('lodgeit', 'secret_key')

        #: bind metadata, create engine and create all tables
        self.engine = engine = db.engine
        #TODO:dc: make this part of the database code
        db.metadata.bind = engine
        db.metadata.create_all(engine, [Paste.__table__])

        #: jinja_environment update
        jinja_environment.globals.update({
            'i18n_languages': i18n.list_languages()})
        jinja_environment.filters.update({
            'datetimeformat': i18n.format_datetime})
        jinja_environment.install_null_translations()

        self.cleanup_callbacks = (db.session.close)
        build_indexer()

    def __call__(self, environ, start_response):
        """Minimal WSGI application for request dispatching."""
        #: bind the application to the new context local
        ctx.application = self
        ctx.request = request = Request(environ)
        ctx.url_adapter = urls = urlmap.bind_to_environ(environ)

        try:
            endpoint, args = urls.match(request.path)
            log.debug('%s %s', request.method, endpoint)
            handler = get_controller(endpoint)
            resp = handler(**args)
        except NotFound:
            handler = get_controller('static/not_found')
            resp = handler()
        except HTTPException, e:
            resp = e.get_response(environ)
        else:
            expires = datetime.utcnow() + timedelta(days=31)
            if request.first_visit or request.session.should_save:
                request.session.save_cookie(resp, COOKIE_NAME,
                                            expires=expires)

        return ClosingIterator(resp(environ, start_response),
                               self.cleanup_callbacks)


def make_app(debug=False, shell=False):
    """Apply the used middlewares and create the application."""
    static_path = os.path.abspath(config.get('lodgeit', 'static_path'))
    app = LodgeIt()
    if debug:
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
    if not shell:
        # we don't need access to the shared data middleware in shell mode
        app = SharedDataMiddleware(app, {'/static': static_path})
    return local_manager.make_middleware(app)