Beispiel #1
0
def main(global_config: Dict[str, str], **settings: str) -> PrefixMiddleware:
    """Configure and return a Pyramid WSGI application."""
    config = Configurator(settings=settings)

    config.include('cornice')
    config.include('pyramid_session_redis')
    config.include('pyramid_webassets')

    # include database first so the session and querying are available
    config.include('tildes.database')
    config.include('tildes.auth')
    config.include('tildes.jinja')
    config.include('tildes.json')
    config.include('tildes.routes')

    config.add_webasset('javascript', Bundle(output='js/tildes.js'))
    config.add_webasset('javascript-third-party',
                        Bundle(output='js/third_party.js'))
    config.add_webasset('css', Bundle(output='css/tildes.css'))
    config.add_webasset('site-icons-css', Bundle(output='css/site-icons.css'))

    config.scan('tildes.views')

    config.add_tween('tildes.http_method_tween_factory')

    config.add_request_method(is_safe_request_method,
                              'is_safe_method',
                              reify=True)

    # Add the request.redis request method to access a redis connection. This
    # is done in a bit of a strange way to support being overridden in tests.
    config.registry['redis_connection_factory'] = get_redis_connection
    # pylint: disable=unnecessary-lambda
    config.add_request_method(
        lambda request: config.registry['redis_connection_factory'](request),
        'redis',
        reify=True,
    )
    # pylint: enable=unnecessary-lambda

    config.add_request_method(check_rate_limit, 'check_rate_limit')

    config.add_request_method(current_listing_base_url,
                              'current_listing_base_url')
    config.add_request_method(current_listing_normal_url,
                              'current_listing_normal_url')

    app = config.make_wsgi_app()

    force_port = global_config.get('prefixmiddleware_force_port')
    if force_port:
        prefixed_app = PrefixMiddleware(app, force_port=force_port)
    else:
        prefixed_app = PrefixMiddleware(app)

    return prefixed_app
Beispiel #2
0
    def main(self):
        from zilch.web import make_webapp
        usage = "usage: %prog database_uri"
        parser = OptionParser(usage=usage)
        parser.add_option("--port",
                          dest="port",
                          type="int",
                          default=8000,
                          help="Port to bind the webserver to")
        parser.add_option("--host",
                          dest="hostname",
                          default="127.0.0.1",
                          help="Hostname/IP to bind the webserver to")
        parser.add_option("--timezone",
                          dest="timezone",
                          default="US/Pacific",
                          help="Default timezone to format dates for")
        parser.add_option("--prefix", dest="prefix", help="URL prefix")
        (options, args) = parser.parse_args()

        if len(args) < 1:
            sys.exit("Error: Failed to provide a database_uri")

        app = make_webapp(args[0], default_timezone=options.timezone)
        if options.prefix:
            from paste.deploy.config import PrefixMiddleware
            app = PrefixMiddleware(app, prefix=options.prefix)
        return serve(app, host=options.hostname, port=options.port)
Beispiel #3
0
def main(global_config: Dict[str, str], **settings: str) -> PrefixMiddleware:
    """Configure and return a Pyramid WSGI application."""
    settings["tildes.open_registration"] = asbool(
        settings.get("tildes.open_registration", "false"))

    config = Configurator(settings=settings)

    config.include("cornice")
    config.include("pyramid_session_redis")
    config.include("pyramid_webassets")

    # include database first so the session and querying are available
    config.include("tildes.database")
    config.include("tildes.auth")
    config.include("tildes.jinja")
    config.include("tildes.json")
    config.include("tildes.request_methods")
    config.include("tildes.routes")
    config.include("tildes.tweens")

    config.add_webasset("javascript", Bundle(output="js/tildes.js"))
    config.add_webasset("javascript-third-party",
                        Bundle(output="js/third_party.js"))
    config.add_webasset("css", Bundle(output="css/tildes.css"))
    config.add_webasset("site-icons-css", Bundle(output="css/site-icons.css"))

    config.scan("tildes.views")

    config.add_static_view("images", "/images")

    if settings.get("sentry_dsn"):
        sentry_sdk.init(
            dsn=settings["sentry_dsn"],
            integrations=[PyramidIntegration()],
            ignore_errors=[ValidationError],
        )

    app = config.make_wsgi_app()

    force_port = global_config.get("prefixmiddleware_force_port")
    if force_port:
        prefixed_app = PrefixMiddleware(app, force_port=force_port)
    else:
        prefixed_app = PrefixMiddleware(app)

    return prefixed_app
Beispiel #4
0
def main():
    logging.info("URL: {}".format(SKIPLAGGED_HOST))
    with Configurator() as config:
        config.add_route('query', '/query')
        config.scan()
        app = config.make_wsgi_app()
        app = PrefixMiddleware(app, prefix='/')
        serve(app, listen='0.0.0.0:8080')
def setup_prefix_middleware(app, global_conf, proxy_prefix):
    """Add prefix middleware.

    Essentially replaces request.environ[SCRIPT_NAME] with the prefix defined
    in the .ini file.

    See: http://wiki.pylonshq.com/display/pylonsdocs/Configuration+Files#prefixmiddleware
    """
    app = PrefixMiddleware(app, global_conf, proxy_prefix)
    return app
Beispiel #6
0
def make_app(global_conf, full_stack=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether or not this application provides a full WSGI stack (by
        default, meaning it handles its own exceptions and errors).
        Disable full_stack when this application is "managed" by
        another WSGI middleware.

    ``app_conf``
        The application's local configuration. Normally specified in the
        [app:<name>] section of the Paste ini file (where <name>
        defaults to main).
    """

    # Configure the Pylons environment
    load_environment(global_conf, app_conf, False)

    # The Pylons WSGI app
    app = PylonsApp()
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if config['pylons.app_globals'].OPT.compressionEnabled:
        app = gzipper(app, config['pylons.app_globals'].OPT.compressionLevel)
    # Static files
    static_app = StaticURLParser(config['pylons.paths']['static_files'])
    app = Cascade([static_app, app])
    prefix = config['pylons.app_globals'].OPT.urlPrefix
    if prefix and prefix.startswith('/') and len(prefix) > 1:
        app = PrefixMiddleware(app, global_conf, prefix=prefix)
    return app
Beispiel #7
0
    def load(self):
        self._load_bzr_plugins()

        with open(os.path.join(config.root,
                               config.codebrowse.secret_path)) as secret_file:
            secret = secret_file.read()

        app = RootApp(SESSION_VAR)
        app = HTTPExceptionHandler(app)
        app = SessionHandler(app, SESSION_VAR, secret)
        app = log_request_start_and_stop(app)
        app = PrefixMiddleware(app)
        app = oops_middleware(app)

        return app
"""
WSGI config for sensible_data_platform project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""
import os
import sys

sys.path.append('/Users/piotr/patrick/SensibleData-Platform/sensible_data_platform')
sys.path.append('/Users/piotr/patrick/SensibleData-Platform')
os.environ["DJANGO_SETTINGS_MODULE"] = "sensible_data_platform.settings"

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

from paste.deploy.config import PrefixMiddleware
application = PrefixMiddleware(application, prefix='/sensible-data/')
Beispiel #9
0
from paste.deploy.config import PrefixMiddleware

import pyramid_api

application = pyramid_api.main({})

# handle proxing headers
application = PrefixMiddleware(application)
Beispiel #10
0
def make_app_for_config_and_path(config, base):
    if config.get_option('trunk_dir') and not config.get_option('user_dirs'):
        print "--trunk-dir is only valid with --user-dirs"
        sys.exit(1)

    if config.get_option('reload'):
        if Reloader.is_installed():
            Reloader.install()
        else:
            return Reloader.restart_with_reloader()

    if config.get_option('user_dirs'):
        if not config.get_option('trunk_dir'):
            print "You didn't specify a directory for the trunk directories."
            sys.exit(1)
        app = UserBranchesFromTransportRoot(base, config)
    else:
        app = BranchesFromTransportRoot(base, config)

    setup_logging(config)

    if config.get_option('profile'):
        from loggerhead.middleware.profile import LSProfMiddleware
        app = LSProfMiddleware(app)
    if config.get_option('memory_profile'):
        from dozer import Dozer
        app = Dozer(app)

    if not config.get_option('user_prefix'):
        prefix = '/'
    else:
        prefix = config.get_option('user_prefix')
        if not prefix.startswith('/'):
            prefix = '/' + prefix

    try:
        from paste.deploy.config import PrefixMiddleware
    except ImportError:
        cant_proxy_correctly_message = (
            'Unsupported configuration: PasteDeploy not available, but '
            'loggerhead appears to be behind a proxy.')

        def check_not_proxied(app):
            def wrapped(environ, start_response):
                if 'HTTP_X_FORWARDED_SERVER' in environ:
                    exc = HTTPInternalServerError()
                    exc.explanation = cant_proxy_correctly_message
                    raise exc
                return app(environ, start_response)

            return wrapped

        app = check_not_proxied(app)
    else:
        app = PrefixMiddleware(app, prefix=prefix)

    app = HTTPExceptionHandler(app)
    app = ErrorHandlerApp(app)
    app = TransLogger(app, logger=logging.getLogger('loggerhead'))

    return app
"""
WSGI config for sensible_explorer project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""
import os
import sys

sys.path.append(
    '/home/marta/SensibleData-Apps-SensibleExplorer/sensible_explorer')
sys.path.append('/home/marta/SensibleData-Apps-SensibleExplorer')
os.environ["DJANGO_SETTINGS_MODULE"] = "sensible_explorer.settings"

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

from paste.deploy.config import PrefixMiddleware
application = PrefixMiddleware(application, prefix='/apps/explorer/')
Beispiel #12
0
"""
WSGI config for data_viewer project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""
import os
import sys

sys.path.append('/home/albert/Development/SensibleData-Auditor/auditor_viewer')
sys.path.append('/home/albert/Development/SensibleData-Auditor')
os.environ["DJANGO_SETTINGS_MODULE"] = "auditor_viewer.settings"

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

from paste.deploy.config import PrefixMiddleware
application = PrefixMiddleware(application, prefix='/albert/apps/auditor_viewer/')
            log.info("Processed ok %s [%0.3f seconds]", url,
                     time.time() - start_time)

        def request_done_err(exc_info):
            log.info("Processed err %s [%0.3f seconds]: %s", url,
                     time.time() - start_time,
                     traceback.format_exception_only(*exc_info[:2]))

        return catch_errors(app, environ, start_response, request_done_err,
                            request_done_ok)

    return wrapped


app = log_request_start_and_stop(app)
app = PrefixMiddleware(app)
app = TransLogger(app)
app = threadpool_debug(app)


def set_scheme(app):
    """Set wsgi.url_scheme in the environment correctly.

    We serve requests that originated from both http and https, and
    distinguish between them by adding a header in the https Apache config.
    """
    def wrapped(environ, start_response):
        environ['wsgi.url_scheme'] = environ.pop('HTTP_X_FORWARDED_SCHEME',
                                                 'http')
        return app(environ, start_response)
Beispiel #14
0
def main(global_config: Dict[str, str], **settings: str) -> PrefixMiddleware:
    """Configure and return a Pyramid WSGI application."""
    config = Configurator(settings=settings)

    config.include("cornice")
    config.include("pyramid_session_redis")
    config.include("pyramid_webassets")

    # include database first so the session and querying are available
    config.include("tildes.database")
    config.include("tildes.auth")
    config.include("tildes.jinja")
    config.include("tildes.json")
    config.include("tildes.routes")

    config.add_webasset("javascript", Bundle(output="js/tildes.js"))
    config.add_webasset("javascript-third-party",
                        Bundle(output="js/third_party.js"))
    config.add_webasset("css", Bundle(output="css/tildes.css"))

    config.scan("tildes.views")

    config.add_tween("tildes.tweens.http_method_tween_factory")
    config.add_tween("tildes.tweens.metrics_tween_factory")
    config.add_tween("tildes.tweens.theme_cookie_tween_factory")

    config.add_static_view("images", "/images")

    config.add_request_method(is_safe_request_method,
                              "is_safe_method",
                              reify=True)

    # Add the request.redis request method to access a redis connection. This is done in
    # a bit of a strange way to support being overridden in tests.
    config.registry["redis_connection_factory"] = get_redis_connection
    # pylint: disable=unnecessary-lambda
    config.add_request_method(
        lambda request: config.registry["redis_connection_factory"](request),
        "redis",
        reify=True,
    )
    # pylint: enable=unnecessary-lambda

    config.add_request_method(check_rate_limit, "check_rate_limit")
    config.add_request_method(apply_rate_limit, "apply_rate_limit")

    config.add_request_method(current_listing_base_url,
                              "current_listing_base_url")
    config.add_request_method(current_listing_normal_url,
                              "current_listing_normal_url")

    if settings.get("sentry_dsn"):
        sentry_sdk.init(
            dsn=settings["sentry_dsn"],
            integrations=[PyramidIntegration()],
            ignore_errors=[ValidationError],
        )

    app = config.make_wsgi_app()

    force_port = global_config.get("prefixmiddleware_force_port")
    if force_port:
        prefixed_app = PrefixMiddleware(app, force_port=force_port)
    else:
        prefixed_app = PrefixMiddleware(app)

    return prefixed_app