Example #1
0
def make_app(mapper, controllers, template_dir=None, debug=False):
   app = Application(controllers, template_dir=template_dir)
   app = AuthenticateMiddleware(app)
   app = RoutesMiddleware(app, mapper)
   app = ErrorDocumentMiddleware(app)
   app = ErrorMiddleware(app, debug=debug)
   return app
    def make_app(global_conf, **app_conf):
        """Returns a Sync Server Application."""
        global_conf.update(app_conf)
        params = convert_config(global_conf)
        app = klass(urls, controllers, params, auth_class)

        if params.get('debug', False):
            app = TransLogger(app, logger_name='syncserver',
                              setup_console_handler=True)

        if params.get('profile', False):
            from repoze.profile.profiler import AccumulatingProfileMiddleware
            app = AccumulatingProfileMiddleware(app,
                                          log_filename='profile.log',
                                          cachegrind_filename='cachegrind.out',
                                          discard_first_request=True,
                                          flush_at_shutdown=True,
                                          path='/__profile__')

        if params.get('client_debug', False):
            # errors are displayed in the user client
            app = ErrorMiddleware(app, debug=True,
                                  show_exceptions_in_wsgi_errors=True)
        else:
            # errors are logged and a 500 is returned with an empty body
            # to avoid any security whole
            app = CatchErrorMiddleware(app, logger_name='syncserver')

        if wrapper is not None:
            app = wrapper(app)
        return app
Example #3
0
def do_request(app, expect_status=500):
    app = lint.middleware(app)
    app = ErrorMiddleware(app, {}, debug=True)
    app = clear_middleware(app)
    testapp = TestApp(app)
    res = testapp.get('', status=expect_status, expect_errors=True)
    return res
Example #4
0
def make_app(global_conf=None):
    from athemeweb.classpublisher import ClassPublisher
    from athemeweb.webroot import WebRoot
    real_app = ClassPublisher(WebRoot())

    from paste.exceptions.errormiddleware import ErrorMiddleware
    error_app = ErrorMiddleware(real_app, global_conf=global_conf)

    from paste.session import SessionMiddleware
    return SessionMiddleware(error_app, global_conf=global_conf)
Example #5
0
def get_wsgi_server():
    flower_app = Flower(capp=scheduler,
                        options=default_options,
                        handlers=handlers,
                        **settings)
    wsgi_app = tornado.wsgi.WSGIAdapter(flower_app)
    wsgi_app = ErrorMiddleware(wsgi_app, debug=debug_flag)
    wsgi_app = TransLogger(wsgi_app, setup_console_handler=debug_flag)

    return wsgi_app
Example #6
0
def server_for_test_app(app):
    try:
        from paste.exceptions.errormiddleware import ErrorMiddleware
        error_app = ErrorMiddleware(app.app, debug=True, error_log="errors.log")
    except ImportError:
        # paste.exceptions not available for Python 3.
        error_app = app
    server = StopableWSGIServer.create(error_app)
    try:
        server.wait()
        yield server
    finally:
        server.shutdown()
Example #7
0
 def build_wsgiapp(self):
     """Build the wsgiapp callable wrapping self.dispatcher with WSGI middlewares"""
     wsgiapp = self.dispatcher
     if self.debug:
         wsgiapp = EvalException(wsgiapp, debug=True)
     elif 'debug_email' in self.config:
         smtp_kwargs = self.config.getAttr('debug_email')
         if 'error_subject_prefix' not in smtp_kwargs:
             smtp_kwargs['error_subject_prefix'] = '[%s] ' % self.site_name
         smtp_kwargs['error_email'] = smtp_kwargs['error_email'].replace(';', ',').split(',')
         if 'smtp_use_tls' in smtp_kwargs:
             smtp_kwargs['smtp_use_tls'] = (smtp_kwargs['smtp_use_tls'] in (True, 'true', 't', 'True', '1', 'TRUE'))
         wsgiapp = ErrorMiddleware(wsgiapp, **smtp_kwargs)
     return wsgiapp
Example #8
0
    def test_expected_exceptions_still_have_cors(self):

        def raises_app(environ, start_response):
            raise IOError('bad')

        catching_app = ErrorMiddleware(raises_app)
        app = cors_filter_factory(catching_app)

        testapp = TestApp(app)
        res = testapp.get('/the_path_doesnt_matter', status=500)

        assert_that(res.normal_body, is_(b'Failed to handle request bad'))

        # Errors set the right response headers
        res = testapp.get('/',
                          extra_environ={
                              'HTTP_ORIGIN': 'http://example.org'},
                          status=500)
        assert_that(res.headers, has_key('Access-Control-Allow-Origin'))
Example #9
0
def server_for_test_app(app):
    try:
        from paste.exceptions.errormiddleware import ErrorMiddleware
        error_app = ErrorMiddleware(app.app, debug=True, error_log="errors.log")
        server = StopableWSGIServer.create(error_app)
    except ImportError:
        # paste.exceptions not available for Python 3.
        error_app = app.app
        server = StopableWSGIServer.create(error_app)
    try:
        server.wait()
        yield server
    finally:
        server.shutdown()
    # There seem to be persistent transient problems with the testing, sleeping
    # between creation of test app instances for greater than .5 seconds seems
    # to help (async loop length in code is .5 so this maybe makes some sense?)
    if "TEST_WEBAPP_POST_SHUTDOWN_SLEEP" in environ:
        time.sleep(int(environ.get("TEST_WEBAPP_POST_SHUTDOWN_SLEEP")))
Example #10
0
def ErrorHandler(app, global_conf, **errorware):
    """ErrorHandler Toggle
    
    If debug is enabled, this function will return the app wrapped in
    our customized Paste EvalException middleware we have called the
    ``PylonsEvalException``.
    
    Otherwise, the app will be wrapped in the Paste ErrorMiddleware, and
    the ``errorware`` dict will be passed into it.
    """
    if asbool(global_conf.get('debug')):
        from pylons.error import PylonsEvalException
        app = PylonsEvalException(app, global_conf, **errorware)
    else:
        from paste.exceptions.errormiddleware import ErrorMiddleware
        if 'error_template' in errorware:
            del errorware['error_template']
        app = ErrorMiddleware(app, global_conf, **errorware)
    return app
Example #11
0
from pecan import conf
from pecan.deploy import deploy
app = deploy('/opt/web/draughtcraft/src/production.py')

from paste.exceptions.errormiddleware import ErrorMiddleware
app = ErrorMiddleware(app,
                      error_email=conf.error_email,
                      from_address=conf.error_email,
                      smtp_server=conf.error_smtp_server,
                      smtp_username=conf.error_email,
                      smtp_password=conf.error_password,
                      smtp_use_tls=True)
import sys, os

INTERP = "/usr/local/bin/python2.7"

if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)

import os, sys, site

site.addsitedir('/home/achilles/site-packages')
site.addsitedir('/home/achilles/rails/khorlo')
#site.addsitedir('/home/achilles/rails')
#site.addsitedir('/home/oskkate/site-packages')
os.environ['LD_LIBRARY_PATH'] = '/usr/local/lib'
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django.core.handlers.wsgi

from paste.exceptions.errormiddleware import ErrorMiddleware

application = django.core.handlers.wsgi.WSGIHandler()
application = ErrorMiddleware(application, debug=True)
Example #13
0
File: main.py Project: xoraxax/dtg
def main():
    parser = optparse.OptionParser()
    parser.add_option('-l',
                      '--location',
                      dest='location',
                      action='store',
                      type="string",
                      help='path prefix to store the database in',
                      default="dtg_")
    parser.add_option('-i',
                      '--server-ip',
                      dest='server_ip',
                      action='store',
                      type="string",
                      help='ip/hostname to run the server on',
                      default="127.0.0.1")
    parser.add_option('-p',
                      '--server-port',
                      dest='server_port',
                      action='store',
                      type="int",
                      help='port to run the server on',
                      default=5005)
    parser.add_option('-e',
                      '--email',
                      dest='email',
                      action='store',
                      type="string",
                      help='e-mail address of the admin',
                      default=None)
    parser.add_option(
        '-P',
        '--path',
        dest='path',
        action='store',
        type="string",
        help=
        'Path of DTG below the HTTP root folder (e.g. PATH in http://SERVERIP:SERVERPORT/PATH/)',
        default=None)
    parser.add_option(
        '-R',
        '--proxy',
        dest='proxy',
        action='store_true',
        help='Proxy mode (use when running behind an HTTP proxy)',
        default=False)
    parser.add_option('-D',
                      '--debug',
                      dest='debug',
                      action='store_true',
                      help='Debug mode',
                      default=False)
    parser.add_option('-M',
                      '--allow-migrations',
                      dest='migrate',
                      action='store_true',
                      help='Allow DB migrations. Only use it with backups :-)',
                      default=False)
    parser.add_option('--add-user',
                      dest='adduser',
                      action='store',
                      type="string",
                      help="Username to add, password will be asked for",
                      default="")
    parser.add_option('--del-user',
                      dest='deluser',
                      action='store',
                      type="string",
                      help="Username to delete",
                      default="")
    parser.add_option('--change-pwd',
                      dest='changepwd',
                      action='store',
                      type="string",
                      help="Username to change password of",
                      default="")

    options, args = parser.parse_args()
    if args:
        parser.error("don't know what to do with additional arguments")

    # HACK! :)

    sys.dtg_db_path = lambda x: "sqlite:///" + os.path.abspath(options.location
                                                               + x + ".db")
    sys.dtg_do_upgrade = options.migrate
    sys.dtg_debug = options.debug

    from dtg.webapp import app, add_user, del_user, change_pwd
    if options.debug:
        app.secret_key = "insecure"

    if options.adduser or options.changepwd:
        password, password2 = getpass(), getpass("Password, again: ")
        if password != password2:
            print "Passwords do not match"
            return
    if options.adduser:
        print add_user(options.adduser, password)
        return
    if options.deluser:
        print del_user(options.deluser)
        return
    if options.changepwd:
        print change_pwd(options.changepwd, password)
        return

    #app.wsgi_app = GzipMiddleware(app.wsgi_app)
    if options.email is not None:
        kwargs = dict(error_email=options.email,
                      from_address=options.email,
                      smtp_server="localhost")
    else:
        kwargs = {}
    app.wsgi_app = ErrorMiddleware(app.wsgi_app, **kwargs)
    if options.path:
        if not options.path.startswith("/"):
            options.path = "/" + options.path
        print "Mounting DTG under", options.path
        app.wsgi_app = DispatcherMiddleware(
            lambda e, s: [s("404 Not found", []), "Not found"][1:],
            mounts={options.path: app.wsgi_app})
    if options.proxy:
        app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run(host=options.server_ip,
            port=options.server_port,
            threaded=True,
            use_reloader=options.debug,
            passthrough_errors=True)
Example #14
0
"""
WSGI config for testproject project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings")

app = get_wsgi_application()

from paste.exceptions.errormiddleware import ErrorMiddleware
application = ErrorMiddleware(app)
Example #15
0
    def getWSGIServer(self):
        wsgi_app = tornado.wsgi.WSGIAdapter(self.flower)
        wsgi_app = ErrorMiddleware(wsgi_app, debug=debug_flag)
        wsgi_app = TransLogger(wsgi_app, setup_console_handler=debug_flag)

        return wsgi_app
Example #16
0
if sys.executable != INTERP:
   os.execl(INTERP, INTERP, *sys.argv)

# Set up the path
sys.stdout = sys.stderr
sys.path.append(site_home)
sys.path.append(os.path.join(site_home,'..'))
sys.path.append(os.path.join(site_home,'project'))
sys.path.append(os.path.join(env_bin,'/lib/python2.6/site-packages'))
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.project.settings" % site_name

# Set up the django application
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

#Define a test application to check that the ErrorMiddleware is working
def testapplication(environ, start_response):
   status = '200 OK'
   output = 'Hello World! Running Python version %s\n\n' % (sys.version)
   response_headers = [('Content-type', 'text/plain'),
                       ('Content-Length', str(len(output)))]

   #Check that the ErrorMiddleware works by uncommenting the next line
   #raise("error")
   start_response(status, response_headers)
   return [output]

from paste.exceptions.errormiddleware import ErrorMiddleware
application = ErrorMiddleware(application, debug=DEBUG)
from objectpub import ObjectPublisher, Root
from paste.exceptions.errormiddleware import ErrorMiddleware
from paste.evalexception import EvalException

app = ObjectPublisher(Root())
#wrapped_app = EvalException(app)
exc_wrapped_app = ErrorMiddleware(app)

if __name__ == '__main__':
    from paste import httpserver
    httpserver.serve(exc_wrapped_app, host='127.0.0.1', port='8079')
Example #18
0
    time.tzset()
    import controller
    application = bottle.default_app()
    application.catchall = False
    if instanceconfig.debug == True:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, evalex=True)
    elif not instanceconfig.debug:
        import paste.exceptions.errormiddleware
        # monkey-patch in logging to datestamped files or gmail
        # the latter is needed when access to datestamped files is impossible
        import exception_logging
        paste.exceptions.errormiddleware.reporter = exception_logging
        from paste.exceptions.errormiddleware import ErrorMiddleware
        application = ErrorMiddleware(
            application,
            debug=False,
            error_log=instanceconfig.exceptionpath,
            error_email=instanceconfig.smtp_to,
            from_address=instanceconfig.smtp_from,
            smtp_server=instanceconfig.smtp_server,
            smtp_username=instanceconfig.smtp_user,
            smtp_password=instanceconfig.smtp_pass,
            error_subject_prefix=instanceconfig.host + ' error:')
except Exception, e:
    print "Couldn't load main app, traceback follows.  Starting config app instead."
    import traceback
    traceback.print_exc()
    import config_app
    application = config_app.app
Example #19
0
import sys, os
sys.path.append(os.getcwd())
sys.path.append(os.getcwd() + '/huxley')

INTERP = os.path.join(os.getcwd(), 'env/bin/python')

if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)

sys.path.insert(0, os.path.join(os.getcwd(), 'env/bin'))
sys.path.insert(
    0, os.path.join(os.getcwd(), 'env/lib/python2.7/site-packages/django'))
sys.path.insert(0, os.path.join(os.getcwd(),
                                'env/lib/python2.7/site-packages'))

os.environ['DJANGO_SETTINGS_MODULE'] = "huxley.settings"

import django
django.setup()

from django.core.handlers.wsgi import WSGIHandler
from paste.exceptions.errormiddleware import ErrorMiddleware
application = ErrorMiddleware(WSGIHandler(), debug=True)
Example #20
0
def make_app(global_conf={}, **app_conf):

    import os, sys
    
    # Cleanup the Python path (mainly to circumvent the systems SetupTools)
    sys.path = [path for path in sys.path if ("site-packages" not in path) and ('pyxer' not in path) and ('/Extras/lib/python' not in path)]
    
    # Add our local packages folder to the path
    import site
    
    here = app_conf.get('pyxer_here') or os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
    if not os.path.isdir(os.path.join(here, 'public')):
        here = os.getcwd()
    
    site_lib = os.path.join(here, 'site-packages')
    site.addsitedir(here)
    site.addsitedir(site_lib)
    # import pkg_resources
    # import setuptools
    
    # log.info(site.__file__)
    # pprint.pprint(global_conf)
    log.debug('\n'.join(sys.path))
    
    try:        
        import beaker.middleware
        global SessionMiddleware
        SessionMiddleware = beaker.middleware.SessionMiddleware
        log.debug("Beaker successfully loaded")
    except ImportError:
        log.debug("Beaker NOT loaded")
        
    conf = AttrDict(pyxer={
        "session": "",
        "debug": False,
        "root": "public",
        })
    root = os.getcwd()
    try:
        import ConfigParser        
        filename = os.path.abspath(global_conf.get("__file__", None)) or os.path.abspath("pyxer.ini")        
        # filename = os.path.abspath("pyxer.ini" )
        root = os.path.dirname(filename)
        cfile = ConfigParser.SafeConfigParser()
        cfile.read(filename)
        for section in cfile.sections():
            if not conf.has_key(section):
                conf[section] = AttrDict()
            try:
                for name, value in cfile.items(section):
                    conf[section][name] = value
            except:
                log.exception("Config items")
        log.debug("Config: %r", conf)
    except:
        log.warning("Config file not found")

    # Add current directory to sys path    
    # site.addsitedir(root)

    # Here we expect all data
    base = os.path.join(root, "public")

    # app = App(global_conf=None, root="public", path=None, **app_conf)
    app = PyxerApp()

    if SessionMiddleware and (conf.get("pyxer.session", "beaker") == "beaker"):
        log.debug("Beaker sessions")
        if "google.appengine" in sys.modules:
            # server = SessionMiddleware(server, type='ext:google', table_name="beaker_session", cookie_expires=False)
            app = SessionMiddleware(app, 
                type='ext:google', 
                table_name='PyxerSession')
        else:
            app = SessionMiddleware(app, 
                type='dbm', 
                data_dir=os.path.join(root, 'cache'))

    app = RegistryManager(app)
    app = ConfigMiddleware(app, conf.copy())

    # app = CgitbMiddleware(app)
    if not stage:
        app = ErrorMiddleware(app, debug=True)

    #static = PyxerStatic(base)
    #app = Cascade([app, static])

    return app
Example #21
0
            guess = int(req.parameters.get("guess", [None])[0])
            if guess < secret_number:
                message = "You guessed %d - which is to low" % guess
            elif guess > secret_number:
                message = "You guessed %d - which is to high" % guess
            else:
                # They got it right so we're done
                break
        except TypeError:
            guess = None
            message = "You must guess a number!"

    return """Yay - %d is the right number, you made it in %d guesses.<br />
    <a href="/">Play again</a>""" % (
        guess,
        number_of_guesses,
    )


if __name__ == "__main__":
    import stacklesswsgi
    from paste.exceptions.errormiddleware import ErrorMiddleware

    exc_wrapped = ErrorMiddleware(SessionlessApp())
    exc_wrapped.debug_mode = True
    import wsgiref.validate

    verify = wsgiref.validate.validator(exc_wrapped)
    s = stacklesswsgi.Server(("127.0.0.1", int(sys.argv[1])), verify)
    s.start()
Example #22
0
CORS(app, resources={r"/*": {"origins": "*"}}, allow_headers=['X-Requested-With', 'Content-Type', 'Authorization', 'user-aws-key', 'Accept', 'Access-Control-Allow-Origin'])

from views.swagger import swagger_bp
from views.user_management import user_management_bp
from app.views.aws.account_management import aws_account_management_bp
from app.views.aws.cost.cost import aws_cost_cost_bp
from app.views.aws.cost.stats import aws_cost_stats_bp
from app.views.aws.forecast import aws_forecast_bp
from app.views.aws.usage import aws_usage_bp
from views.google import google_bp
from views.ms_azure import ms_azure_bp
from views.compare_providers import compare_providers_bp
import views.health

app.register_blueprint(swagger_bp)
app.register_blueprint(user_management_bp)
app.register_blueprint(aws_account_management_bp)
app.register_blueprint(aws_cost_cost_bp)
app.register_blueprint(aws_cost_stats_bp)
app.register_blueprint(aws_forecast_bp)
app.register_blueprint(aws_usage_bp)
app.register_blueprint(google_bp)
app.register_blueprint(ms_azure_bp)
app.register_blueprint(compare_providers_bp)

if app.debug:
    from paste.exceptions.errormiddleware import ErrorMiddleware
    wsgi = ErrorMiddleware(app, debug=True)
else:
    wsgi = app
Example #23
0
def _make_core_app(root, global_conf, full_stack=True, **app_conf):
    """
    Set allura up with the settings found in the PasteDeploy configuration
    file used.

    :param root: The controller module containing the TG root
    :param global_conf: The global settings for allura (those
        defined under the ``[DEFAULT]`` section).
    :type global_conf: dict
    :param full_stack: Should the whole TG2 stack be set up?
    :type full_stack: str or bool
    :return: The allura application with all the relevant middleware
        loaded.

    This is the PasteDeploy factory for the allura application.

    ``app_conf`` contains all the application-specific settings (those defined
    under ``[app:main]``.


    """
    # Run all the initialization code here
    mimetypes.init([pkg_resources.resource_filename('allura', 'etc/mime.types')] + mimetypes.knownfiles)

    # Configure MongoDB
    ming.configure(**app_conf)

    # Configure ActivityStream
    if asbool(app_conf.get('activitystream.recording.enabled', False)):
        activitystream.configure(**h.convert_bools(app_conf, prefix='activitystream.'))

    # Configure EW variable provider
    ew.render.TemplateEngine.register_variable_provider(get_tg_vars)

    # Set FormEncode language to english, as we don't support any other locales
    formencode.api.set_stdtranslation(domain='FormEncode', languages=['en'])

    # Create base app
    base_config = ForgeConfig(root)
    load_environment = base_config.make_load_environment()

    # Code adapted from tg.configuration, replacing the following lines:
    #     make_base_app = base_config.setup_tg_wsgi_app(load_environment)
    #     app = make_base_app(global_conf, full_stack=True, **app_conf)

    # Configure the TG environment
    load_environment(global_conf, app_conf)

    app = tg.TGApp()

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'inner':
            app = Middleware(app, config)

    # Required for sessions
    app = SessionMiddleware(app, config, data_serializer=BeakerPickleSerializerWithLatin1())
    # Handle "Remember me" functionality
    app = RememberLoginMiddleware(app, config)
    # Redirect 401 to the login page
    app = LoginRedirectMiddleware(app)
    # Add instrumentation
    app = AlluraTimerMiddleware(app, app_conf)
    # Clear cookies when the CSRF field isn't posted
    if not app_conf.get('disable_csrf_protection'):
        app = CSRFMiddleware(app, '_session_id')
    if asbool(config.get('cors.enabled', False)):
        # Handle CORS requests
        allowed_methods = aslist(config.get('cors.methods'))
        allowed_headers = aslist(config.get('cors.headers'))
        cache_duration = asint(config.get('cors.cache_duration', 0))
        app = CORSMiddleware(app, allowed_methods, allowed_headers, cache_duration)
    # Setup the allura SOPs
    app = allura_globals_middleware(app)
    # Ensure http and https used per config
    if config.get('override_root') != 'task':
        app = SSLMiddleware(app, app_conf.get('no_redirect.pattern'),
                            app_conf.get('force_ssl.pattern'),
                            app_conf.get('force_ssl.logged_in'))
    # Setup resource manager, widget context SOP
    app = ew.WidgetMiddleware(
        app,
        compress=True,
        use_cache=not asbool(global_conf['debug']),
        script_name=app_conf.get('ew.script_name', '/_ew_resources/'),
        url_base=app_conf.get('ew.url_base', '/_ew_resources/'),
        extra_headers=ast.literal_eval(app_conf.get('ew.extra_headers', '[]')),
        cache_max_age=asint(app_conf.get('ew.cache_header_seconds', 60*60*24*365)),

        # settings to pass through to jinja Environment for EW core widgets
        # these are for the easywidgets' own [easy_widgets.engines] entry point
        # (the Allura [easy_widgets.engines] entry point is named "jinja" (not jinja2) but it doesn't need
        #  any settings since it is a class that uses the same jinja env as the rest of allura)
        **{
            'jinja2.auto_reload': asbool(config['auto_reload_templates']),
            'jinja2.bytecode_cache': AlluraJinjaRenderer._setup_bytecode_cache(),
            'jinja2.cache_size': asint(config.get('jinja_cache_size', -1)),
        }
    )
    # Handle static files (by tool)
    app = StaticFilesMiddleware(app, app_conf.get('static.script_name'))
    # Handle setup and flushing of Ming ORM sessions
    app = MingMiddleware(app)
    # Set up the registry for stacked object proxies (SOPs).
    #    streaming=true ensures they won't be cleaned up till
    #    the WSGI application's iterator is exhausted
    app = RegistryManager(app, streaming=True)

    # "task" wsgi would get a 2nd request to /error/document if we used this middleware
    if config.get('override_root') not in ('task', 'basetest_project_root'):
        if asbool(config['debug']):
            # Converts exceptions to HTTP errors, shows traceback in debug mode
            # don't use TG footer with extra CSS & images that take time to load
            tg.error.footer_html = '<!-- %s %s -->'
            app = tg.error.ErrorHandler(app, global_conf, **config['tg.errorware'])
        else:
            app = ErrorMiddleware(app, config, **config['tg.errorware'])

        app = SetRequestHostFromConfig(app, config)

        # Redirect some status codes to /error/document
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, base_config.handle_status_codes)
        else:
            app = StatusCodeRedirect(
                app, base_config.handle_status_codes + [500])

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'outer':
            app = Middleware(app, config)

    return app
Example #24
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paste
import cherrypy
from server import app

from paste.exceptions.errormiddleware import ErrorMiddleware
from paste.translogger import TransLogger

if __name__ == "__main__":
    app = ErrorMiddleware(app, debug=False)
    app = TransLogger(app, setup_console_handler=True)

    cherrypy.tree.graft(app, '')
    cherrypy.config.update({
        'engine.autoreload_on': False,
        'server.socket_port': 4000,
        'server.socket_host': '0.0.0.0',
        'server.thread_pool': 5,
    })

    cherrypy.engine.signals.subscribe()
    cherrypy.engine.start()
    cherrypy.engine.block()