Пример #1
0
def main():
    try:
        ccname = get_ccname()
    except ValueError as e:
        print("ERROR:", e, file=sys.stderr)
        print(
            "\nliteserver requires a KRB5CCNAME env var and "
            "a valid Kerberos TGT:\n",
            file=sys.stderr)
        print("    export KRB5CCNAME=~/.ipa/ccache", file=sys.stderr)
        print("    kinit\n", file=sys.stderr)
        sys.exit(1)

    init_api()

    if os.path.isfile(api.env.lite_pem):
        ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
        ctx.load_cert_chain(api.env.lite_pem)
    else:
        ctx = None

    app = NotFound()
    app = DispatcherMiddleware(
        app, {
            '/ipa': KRBCheater(api.Backend.wsgi_dispatch, ccname),
        })

    # only profile api calls
    if api.env.lite_profiler == '-':
        print('Profiler enable, stats are written to stderr.')
        app = ProfilerMiddleware(app, stream=sys.stderr, restrictions=(30, ))
    elif api.env.lite_profiler:
        profile_dir = os.path.abspath(api.env.lite_profiler)
        print("Profiler enable, profiles are stored in '{}'.".format(
            profile_dir))
        app = ProfilerMiddleware(app, profile_dir=profile_dir)

    app = StaticFilesMiddleware(app, STATIC_FILES)
    app = redirect_ui(app)

    run_simple(
        hostname=api.env.lite_host,
        port=api.env.lite_port,
        application=app,
        processes=5,
        ssl_context=ctx,
        use_reloader=True,
        # debugger doesn't work because framework catches all exceptions
        # use_debugger=not api.env.webui_prod,
        # use_evalex=not api.env.webui_prod,
    )
Пример #2
0
    def __init__(self, listen_port, handlers, parameters, shard=0,
                 listen_address=""):
        super(WebService, self).__init__(shard)

        static_files = parameters.pop('static_files', [])
        rpc_enabled = parameters.pop('rpc_enabled', False)
        rpc_auth = parameters.pop('rpc_auth', None)
        auth_middleware = parameters.pop('auth_middleware', None)
        is_proxy_used = parameters.pop('is_proxy_used', None)
        num_proxies_used = parameters.pop('num_proxies_used', None)

        self.wsgi_app = tornado.wsgi.WSGIApplication(handlers, **parameters)
        self.wsgi_app.service = self

        for entry in static_files:
            # TODO If we will introduce a flag to trigger autoreload in
            # Jinja2 templates, use it to disable the cache arg here.
            self.wsgi_app = SharedDataMiddleware(
                self.wsgi_app, {"/static": entry},
                cache=True, cache_timeout=SECONDS_IN_A_YEAR,
                fallback_mimetype="application/octet-stream")

        if rpc_enabled:
            self.wsgi_app = DispatcherMiddleware(
                self.wsgi_app, {"/rpc": RPCMiddleware(self, rpc_auth)})

        # The authentication middleware needs to be applied before the
        # ProxyFix as otherwise the remote address it gets is the one
        # of the proxy.
        if auth_middleware is not None:
            self.wsgi_app = auth_middleware(self.wsgi_app)
            self.auth_handler = self.wsgi_app

        # If we are behind one or more proxies, we'll use the content
        # of the X-Forwarded-For HTTP header (if provided) to determine
        # the client IP address, ignoring the one the request came from.
        # This allows to use the IP lock behind a proxy. Activate it
        # only if all requests come from a trusted source (if clients
        # were allowed to directlty communicate with the server they
        # could fake their IP and compromise the security of IP lock).
        if num_proxies_used is None:
            if is_proxy_used:
                num_proxies_used = 1
            else:
                num_proxies_used = 0

        if num_proxies_used > 0:
            self.wsgi_app = ProxyFix(self.wsgi_app, num_proxies_used)

        self.web_server = WSGIServer((listen_address, listen_port), self)
Пример #3
0
    def run(self, host=None, port=None, debug=None, **options):
        import tornado.wsgi
        import tornado.ioloop
        import tornado.httpserver
        import tornado.web

        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = self.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000
        if debug is not None:
            self.debug = bool(debug)

        hostname = host
        port = port
        application = self
        use_reloader = self.debug
        use_debugger = self.debug

        # 使用werkzeug可以解决uWSGI下debug flask的问题
        # https://codeseekah.com/2012/10/28/dubugging-flask-applications-under-uwsgi/
        if use_debugger:
            from werkzeug.debug import DebuggedApplication
            application = DebuggedApplication(application, True)

        try:
            from .webdav import dav_app
        except ImportError as e:
            logger.warning('WebDav interface not enabled: %r', e)
            dav_app = None
        if dav_app:
            from werkzeug.wsgi import DispatcherMiddleware
            application = DispatcherMiddleware(application, {
                '/dav': dav_app
            })

        container = tornado.wsgi.WSGIContainer(application)
        self.http_server = tornado.httpserver.HTTPServer(container)
        self.http_server.listen(port, hostname)
        if use_reloader:
            from tornado import autoreload
            autoreload.start()

        self.logger.info('webui running on %s:%s', hostname, port)
        self.ioloop = tornado.ioloop.IOLoop.current()
        self.ioloop.start()
Пример #4
0
def main(filenames, port, host, prefix, incognito, debug, profile,
         profile_dir):
    """Start Fava for FILENAMES on http://<host>:<port>.

    If the `BEANCOUNT_FILE` environment variable is set, Fava will use the
    files (space-delimited) specified there in addition to FILENAMES.
    """

    if profile:  # pragma: no cover
        debug = True

    env_filename = os.environ.get('BEANCOUNT_FILE')
    if env_filename:
        filenames = filenames + tuple(env_filename.split())

    if not filenames:
        raise click.UsageError('No file specified')

    app.config['BEANCOUNT_FILES'] = filenames
    app.config['INCOGNITO'] = incognito

    if prefix:
        app.wsgi_app = DispatcherMiddleware(simple_wsgi,
                                            {prefix: app.wsgi_app})

    if not debug:
        server = wsgi.Server((host, port), app)
        print('Running Fava on http://{}:{}'.format(host, port))
        server.safe_start()
    else:
        if profile:
            from werkzeug.contrib.profiler import ProfilerMiddleware

            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(30, ),
                profile_dir=profile_dir if profile_dir else None,
            )

        app.jinja_env.auto_reload = True
        try:
            app.run(host, port, debug)
        except OSError as error:
            if error.errno == errno.EADDRINUSE:
                raise click.UsageError(
                    "Can not start webserver because the port is already in "
                    "use. Please choose another port with the '-p' option.")
            else:  # pragma: no cover
                raise
Пример #5
0
def create_app():
    app = Flask(__name__, template_folder='templates',
                static_folder='static')
    app.config.from_object(config)
    mako.init_app(app)
    db.init_app(app)
    app.session_interface = RedisSessionInterface(cache)
    app.register_blueprint(backend.bp)

    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, OrderedDict((
        ('/j', json_api),
    )))

    return app
Пример #6
0
    def __call__(self, environ, start_response):
        """Handle a request for base app + extra apps."""
        from werkzeug.wsgi import DispatcherMiddleware

        if not self.hass.is_running:
            from werkzeug.exceptions import BadRequest
            return BadRequest()(environ, start_response)

        app = DispatcherMiddleware(self.base_app, self.extra_apps)
        # Strip out any cachebusting MD5 fingerprints
        fingerprinted = _FINGERPRINT.match(environ.get('PATH_INFO', ''))
        if fingerprinted:
            environ['PATH_INFO'] = "{}.{}".format(*fingerprinted.groups())
        return app(environ, start_response)
Пример #7
0
def main(filenames, port, host, prefix, debug, profile, profile_dir,
         profile_restriction):
    """Start Fava for FILENAMES on http://host:port.

    If the `BEANCOUNT_FILE` environment variable is set, Fava will use the file
    specified there in addition to FILENAMES.
    """

    if profile_dir:  # pragma: no cover
        profile = True
    if profile:  # pragma: no cover
        debug = True

    env_filename = os.environ.get('BEANCOUNT_FILE')
    if env_filename:
        filenames = filenames + (env_filename, )

    if not filenames:
        raise click.UsageError('No file specified')

    app.config['BEANCOUNT_FILES'] = filenames

    load_file()

    if prefix:
        app.wsgi_app = DispatcherMiddleware(simple_wsgi,
                                            {prefix: app.wsgi_app})

    if debug:  # pragma: no cover
        if profile:
            # pylint: disable=redefined-variable-type
            from werkzeug.contrib.profiler import ProfilerMiddleware
            app.config['PROFILE'] = True
            app.wsgi_app = ProfilerMiddleware(
                app.wsgi_app,
                restrictions=(profile_restriction, ),
                profile_dir=profile_dir if profile_dir else None)

        app.jinja_env.auto_reload = True

    try:
        app.run(host, port, debug)
    except OSError as error:
        if error.errno == errno.EADDRINUSE:
            raise click.UsageError(
                "Can not start webserver because the port is already in "
                "use. Please choose another port with the '-p' option.")
        else:  # pragma: no cover
            raise
Пример #8
0
def create_app():
    logging.basicConfig(level=logging.DEBUG)
    app = Flask(__name__)
    app.config.from_object('api.default.settings')
    app.db = DBAPI(globals.DB_MIN_CONN, globals.DB_MAX_CONN, dsn=globals.DSN)

    logger.debug('Starting RESTful API on URL {}'.format(globals.REST_URL))
    app.register_blueprint(rest, url_prefix=globals.REST_URL)

    logger.debug('Starting SOAP API on URL {}'.format(globals.SOAP_URL))
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app,
            {globals.SOAP_URL : create_soap_wsgi(app.db)})

    app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)
    return app
Пример #9
0
def create_app(config_object=ProdConfig):
    app = Flask(__name__.split(".")[0])
    app.config.from_object(config_object)
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    register_shellcontext(app)
    register_commands(app)
    jinja_global_varibles(app)
    log_slow_queries(app)

    app.wsgi_app = DispatcherMiddleware(
        app.wsgi_app, {"/dashboard_api": dashboard_api.api_app.dashboard_api})

    return app
Пример #10
0
 def WSGIHandler(self):
     """Returns GRR's WSGI handler."""
     sdm = SharedDataMiddleware(self, {
         "/": config.CONFIG["AdminUI.document_root"],
     })
     # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not
     # used at all if the URL path doesn't start with "/static". This is a
     # workaround for cases when unicode URLs are used on systems with
     # non-unicode filesystems (as detected by Werkzeug). In this case
     # SharedDataMiddleware may fail early while trying to convert the
     # URL into the file path and not dispatch the call further to our own
     # WSGI handler.
     return DispatcherMiddleware(self, {
         "/static": sdm,
     })
Пример #11
0
def start_app():
    app.config['DEBUG'] = args.debug
    app.config['args'] = args
    if args.root and args.root != '/':
        if not args.root.startswith('/'):
            args.root = '/' + args.root
        from werkzeug.serving import run_simple
        from werkzeug.wsgi import DispatcherMiddleware
        app.config["APPLICATION_ROOT"] = args.root
        application = DispatcherMiddleware(simple, {
            app.config['APPLICATION_ROOT']: app,
        })
        run_simple(args.listen, args.port, application, use_reloader=args.debug)
    else:
        app.run(args.listen, args.port, debug=args.debug)
Пример #12
0
    def run(self, host=None, port=None, debug=None, **options):
        from werkzeug.serving import make_server, run_with_reloader

        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = self.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000
        if debug is not None:
            self.debug = bool(debug)

        hostname = host
        port = port
        application = self
        use_reloader = self.debug
        use_debugger = self.debug

        if use_debugger:
            from werkzeug.debug import DebuggedApplication
            application = DebuggedApplication(application, True)

        try:
            from .webdav import dav_app
        except ImportError as e:
            logger.error('WebDav interface not enabled: %r', e)
            dav_app = None
        if dav_app:
            from werkzeug.wsgi import DispatcherMiddleware
            application = DispatcherMiddleware(application, {'/dav': dav_app})

        def inner():
            self.server = make_server(hostname, port, application)
            self.server.serve_forever()

        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            display_hostname = hostname != '*' and hostname or 'localhost'
            if ':' in display_hostname:
                display_hostname = '[%s]' % display_hostname
            self.logger.info('webui running on http://%s:%d/',
                             display_hostname, port)

        if use_reloader:
            run_with_reloader(inner)
        else:
            inner()
Пример #13
0
def start_web():
  check_requirements()

  import flux
  from flux import app, config, utils

  app.jinja_env.globals['config'] = config
  app.jinja_env.globals['flux'] = flux
  app.secret_key = config.secret_key
  app.config['DEBUG'] = config.debug
  app.config['SERVER_NAME'] = config.server_name
  print('DEBUG = {}'.format(config.debug))
  print('SERVER_NAME = {}'.format(config.server_name))

  from flux import views, build, models
  from urllib.parse import urlparse

  # Ensure that some of the required directories exist.
  for dirname in [config.root_dir, config.build_dir, config.override_dir, config.customs_dir]:
    if not os.path.exists(dirname):
        os.makedirs(dirname)

  # Make sure the root user exists and has all privileges, and that
  # the password is up to date.
  with models.session():
    models.User.create_or_update_root()

  # Create a dispatcher for the sub-url under which the app is run.
  url_prefix = urlparse(config.app_url).path
  if url_prefix and url_prefix != '/':
    import flask
    from werkzeug.wsgi import DispatcherMiddleware
    target_app = DispatcherMiddleware(flask.Flask('_dummy_app'), {
      url_prefix: app,
    })
  else:
    target_app = app

  app.logger.info('Starting builder threads...')
  build.run_consumers(num_threads=config.parallel_builds)
  build.update_queue()
  try:
    from werkzeug.serving import run_simple
    run_simple(config.host, config.port, target_app,
      use_debugger=config.debug, use_reloader=False)
  finally:
    app.logger.info('Stopping builder threads...')
    build.stop_consumers()
Пример #14
0
def run_gunicorn():
    from app import create_app
    app = create_app()
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app,
                                        {'/metrics': make_wsgi_app()})
    pprint(app.url_map)
    options = {
        'bind': '0.0.0.0:2333',
        'workers': G_WORKER_NUM,
        # gevent worker will cause captain can't create unix daemon
        # 'worker_class': 'gevent',
        'accesslog': '-',
        'errorlog': '-',
        'timeout': 300,
    }
    StandaloneApplication(app, options).run()
Пример #15
0
def add_metrics_endpoint(app):
    """
    This function dispatches Prometheus WSGI App
    Usage example:

    from prometheus_toolbox.expose.flask import add_metrics_endpoint
    app = Flask(__name__)
    app = add_metrics_endpoint(app)

    :param app: app instance
    :return: app instance with metrics endpoint
    """
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
        '/metrics': create_wsgi_app(),
    })
    return app
Пример #16
0
    def __init__(self, url, service_impl_cls):
        self.url = url_endswith_slash(url)
        self.scheme, self.host, self.path, _, _ = urllib.parse.urlsplit(
            self.url)

        def null_app(environ, start_response):
            start_response('404 Not Found', [('Content-Type', 'text/plain')])
            return ['Not Found']

        wsgi_app = WsgiApp(service_impl_cls())
        if self.path != '/':
            self.wsgi_app = DispatcherMiddleware(null_app,
                                                 {self.path[:-1]: wsgi_app})
        else:
            self.wsgi_app = wsgi_app
        self.wsgi_test_client = Client(self.wsgi_app, Response)
Пример #17
0
    def __init__(self, app):
        self.publisher = Publisher(get_library_registry())

        app.before_request(self.before_request)
        teardown_request = getattr(app, 'teardown_request', app.after_request)
        teardown_request(self.teardown_request)

        options = app.config.get('FANSTATIC_OPTIONS', {})
        publisher_signature = options.get('publisher_signature',
                                          DEFAULT_SIGNATURE)

        app.wsgi_app = DispatcherMiddleware(
            app.wsgi_app, {
                '/%s' % publisher_signature: self.publisher,
            })

        self.resource_sets = {}
Пример #18
0
    def run(self):
        views.create_views(self)

        app_root = self.flask.config.get("APPLICATION_ROOT")
        if app_root:
            def simple(env, resp):
                resp(b'200 OK', [(b'Content-Type', b'text/html')])
                return [b'<a href="{root}">{root}</a>'.format(root=app_root)]
            print self.flask.config["APPLICATION_ROOT"]
            self.flask.wsgi_app = DispatcherMiddleware(simple, {
                self.flask.config["APPLICATION_ROOT"]: self.flask.wsgi_app
            })
        # Add extra files
        extra_files = []
        for (root, _, files) in os.walk(os.path.join(const.PUSH_WEB_DIR, "templates")):
            extra_files.extend(os.path.join(root, f) for f in files)
        self.flask.run(self.host, self.port, debug=self.debug, extra_files=extra_files)
Пример #19
0
def run(port=5000,
        mongo_host='localhost',
        mongo_port=27017,
        pagination_limit=1000000):
    client = j.clients.osis.getByInstance('main')

    apps = dict()

    for namespace in client.listNamespaces():
        spec = client.getOsisSpecModel(namespace)
        dbname = namespace if namespace != 'system' else 'js_system'
        my_settings = {
            'MONGO_HOST': mongo_host,
            'MONGO_PORT': mongo_port,
            'MONGO_DBNAME': dbname,
            'DOMAIN': generateDomain(spec),
            'RESOURCE_METHODS': ['GET', 'POST'],
            'ITEM_METHODS': ['GET', 'PATCH', 'PUT', 'DELETE'],
            'X_DOMAINS': '*',
            'MONGO_QUERY_BLACKLIST': [],
            'X_HEADERS': ["X-HTTP-Method-Override", 'If-Match'],
            'PAGINATION_LIMIT': pagination_limit
        }

        # init application
        app = Eve(__name__, settings=my_settings)

        Bootstrap(app)

        @app.route('/ui')
        def ui():
            return render_template('ui.html')

        # Unfortunately, eve_docs doesn't support CORS (too bad!), so we had to reimplement it ourselves
        @app.route('/docs/spec.json')
        def specs():
            return send_response(None, [get_cfg()])

        apps['/%s' % namespace] = app

    print "visit:\nhttp://localhost:%s/docs/" % port
    if apps:
        firstapp = apps.values()[0]
        application = DispatcherMiddleware(firstapp, apps)
        # let's roll
        run_simple('0.0.0.0', port, application, use_reloader=False)
Пример #20
0
    def __init__(self,
                 listen_port,
                 handlers,
                 parameters,
                 shard=0,
                 listen_address=""):
        super(WebService, self).__init__(shard)

        static_files = parameters.pop('static_files', [])
        rpc_enabled = parameters.pop('rpc_enabled', False)
        rpc_auth = parameters.pop('rpc_auth', None)
        auth_middleware = parameters.pop('auth_middleware', None)
        is_proxy_used = parameters.pop('is_proxy_used', False)

        self.wsgi_app = tornado.wsgi.WSGIApplication(handlers, **parameters)
        self.wsgi_app.service = self

        for entry in static_files:
            self.wsgi_app = SharedDataMiddleware(self.wsgi_app,
                                                 {"/static": entry})

        if rpc_enabled:
            self.wsgi_app = DispatcherMiddleware(
                self.wsgi_app, {"/rpc": RPCMiddleware(self, rpc_auth)})

        # Remove any authentication header that a user may try to fake.
        self.wsgi_app = HeaderRewriterFix(
            self.wsgi_app,
            remove_headers=[WebService.AUTHENTICATED_USER_HEADER])

        if auth_middleware is not None:
            self.wsgi_app = auth_middleware(self.wsgi_app)

        # If is_proxy_used is set to True we'll use the content of the
        # X-Forwarded-For HTTP header (if provided) to determine the
        # client IP address, ignoring the one the request came from.
        # This allows to use the IP lock behind a proxy. Activate it
        # only if all requests come from a trusted source (if clients
        # were allowed to directlty communicate with the server they
        # could fake their IP and compromise the security of IP lock).
        if is_proxy_used:
            self.wsgi_app = ProxyFix(self.wsgi_app)

        self.web_server = WSGIServer((listen_address, listen_port),
                                     self.wsgi_app)
Пример #21
0
def main():

    if cfg.is_debug:
        app.config['DEBUG'] = True

    if APPLICATION_ROOT == '/':
        app.run(host=cfg.host_bind,
                port=cfg.port_bind,
                use_reloader=True,
                extra_files=[cfg.path_config_file])
    else:
        application = DispatcherMiddleware(Flask('dummy_app'), {
            app.config['APPLICATION_ROOT']: app,
        })
        run_simple(cfg.host_bind,
                   cfg.port_bind,
                   application,
                   use_reloader=True,
                   extra_files=[cfg.path_config_file])
Пример #22
0
def start(basedir, hrd):
    port = hrd.getInt('instance.param.osis2.port')
    mongdb_instance = hrd.get('instance.param.osis2.mongodb.connection', '')
    sqluri = hrd.get('instance.param.osis2.sqlalchemy.uri', '')
    use_reloader = hrd.getBool('instance.param.osis2.use_reloader')
    use_debugger = hrd.getBool('instance.param.osis2.use_debugger')

    if mongdb_instance:
        mongohrd = j.application.getAppInstanceHRD('mongodb_client',
                                                   mongdb_instance)
        BASE_SETTINGS['MONGO_HOST'] = mongohrd.get('instance.param.addr')
        BASE_SETTINGS['MONGO_PORT'] = mongohrd.getInt('instance.param.port')

    apps = dict()

    fullspecs = modelloader.find_model_specs(basedir)
    namespaces = []
    for type_, specs in fullspecs.iteritems():
        for namespace, models in specs.iteritems():
            if type_ == 'sql':
                app = prepare_sqlapp(namespace, models, sqluri)
            else:
                app = prepare_mongoapp(namespace, models)
            apps['/models/%s' % namespace] = app
            namespaces.append(namespace)

    # Auto load sqlalchemy models from python files
    spaces_models = modelloader.find_model_files(basedir)
    for namespace, models in spaces_models.iteritems():
        app = prepare_sqlapp(namespace, models, sqluri, False)
        apps['/models/%s' % namespace] = app
        namespaces.append(namespace)

    if apps:
        apiapp = api.register_api(namespaces)
        apps['/api'] = apiapp
        application = DispatcherMiddleware(apiapp, apps)
        # let's roll
        run_simple('0.0.0.0',
                   port,
                   application,
                   use_reloader=use_reloader,
                   use_debugger=use_debugger)
Пример #23
0
def create():
    config = Config()
    app = QlessPyapi(config)

    if config['ui']:
        app.wsgi_app = DispatcherMiddleware(
            app.wsgi_app, {
                '/api':
                app.wsgi_app,
                '/app':
                SharedDataMiddleware(redirect('/app/index.html'), {
                    '/':
                    path.join(path.dirname(__file__), 'qless-ui', 'app')
                }),
                '/':
                redirect('/app/index.html')
            })

    return app, config
Пример #24
0
    def start(self):
        """
        Start the server.
        """
        plugins = voltron.plugin.pm.web_plugins
        self.app = DispatcherMiddleware(
            VoltronFlaskApp('voltron',
                            template_folder='web/templates',
                            static_folder='web/static',
                            server=self),
            {
                "/view":
                SharedDataMiddleware(
                    None, {
                        '/{}'.format(n): os.path.join(p._dir, 'static')
                        for (n, p) in six.iteritems(plugins)
                    }),
                "/ui":
                ui_app
            })

        def run_listener(name, cls, arg):
            log.debug("Starting listener for {} socket on {}".format(
                name, str(arg)))
            s = cls(*arg)
            t = threading.Thread(target=s.serve_forever)
            t.start()
            self.threads.append(t)
            self.listeners.append(s)

        if voltron.config.server.listen.tcp:
            run_listener('tcp', ThreadedVoltronWSGIServer,
                         list(voltron.config.server.listen.tcp) + [self.app])

        if voltron.config.server.listen.domain:
            path = os.path.expanduser(str(voltron.config.server.listen.domain))
            try:
                os.unlink(path)
            except:
                pass
            run_listener('domain', ThreadedUnixWSGIServer, [path, self.app])

        self.is_running = True
Пример #25
0
def initialize_frontend(global_config, use_analytics=False):
    '''Frontend server with all portal pages and required resources
    '''

    docs_app = static.Cling(resource_filename('pdp', 'docs/html'))
    static_app = static.Cling(resource_filename('pdp', 'static'))

    mounts = {app.url_base: app.mk_frontend(global_config) for app in apps}
    mounts.update({
        '/pcds_map': pcds.mk_frontend(global_config),  # legacy url support
        '/css/': static.Cling(resource_filename('pdp_util', 'data')),
        '/docs': docs_app
    })

    wsgi_app = DispatcherMiddleware(static_app, mounts)

    if use_analytics:
        wsgi_app = AnalyticsMiddleware(wsgi_app, global_config['analytics'])
    return ErrorMiddleware(wsgi_app)
Пример #26
0
def main():

    # Set reloader to False, bug present for imports
    # Retain this as FIXME
    # https://github.com/mitsuhiko/flask/issues/1246
    reloader = False

    if cfg.is_debug:
        app.config['DEBUG'] = True
        uqpanel.add_debug_toolbar(app)

    if cfg.queues_for_reset_stats():
        if job.check_connect_redis():
            rq_worker.start_jobs()
        else:
            print("Error: There not connection to Redis")
            print("       Reset stats will not work\n")

    if PY2:
        # This change is a fix for issue with Python 2.7
        # The error is IOError: [Errno 32] Broken pipe
        # All this shit happend if the connection is closed early
        # by remove client (browser)
        # Long story https://github.com/pallets/werkzeug/issues/954
        from gevent.wsgi import WSGIServer
        http_server = WSGIServer((cfg.host_bind, cfg.port_bind), app)
        http_server.serve_forever()

    if cfg.base_url == '/':
        app.run(host=cfg.host_bind,
                port=cfg.port_bind,
                use_reloader=reloader,
                extra_files=[cfg.path_config_file])
    else:
        application = DispatcherMiddleware(Flask('dummy_app'), {
            app.config['APPLICATION_ROOT']: app,
        })
        run_simple(cfg.host_bind,
                   cfg.port_bind,
                   application,
                   use_reloader=reloader,
                   extra_files=[cfg.path_config_file])
Пример #27
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('spyne.wsgi').setLevel(logging.DEBUG)

    filemgr_app = WsgiApplication(Application([FileServices],
            tns='spyne.examples.file_manager',
            in_protocol=HttpRpc(validator='soft'),
            out_protocol=HttpRpc()
        ))

    try:
        os.makedirs('./files')
    except OSError:
        pass

    wsgi_app = DispatcherMiddleware(NotFound(), {'/filemgr': filemgr_app})

    logger.info("navigate to: http://localhost:9000/index.html")
    return run_simple('localhost', port, wsgi_app, static_files={'/': 'static'},
                                                                  threaded=True)
Пример #28
0
def create_combined_app(*args, **kw):
    from werkzeug.wsgi import DispatcherMiddleware

    frontend = create_frontend_app(*args, **kw)
    api = create_api_app(*args, **kw)

    mounts = {
        '/api': api,
    }

    if frontend.config.get('SKYLINES_MAPPROXY'):
        from mapproxy.wsgiapp import make_wsgi_app as create_mapproxy_app

        mapproxy = create_mapproxy_app(
            frontend.config.get('SKYLINES_MAPPROXY'))

        mounts['/mapproxy'] = mapproxy

    frontend.wsgi_app = DispatcherMiddleware(frontend.wsgi_app, mounts)
    return frontend
Пример #29
0
    def execute_api_server(self,
                           listen_address=None,
                           listen_port=None,
                           ssl_cert=None,
                           ssl_key=None):

        # https://gist.github.com/rduplain/1705072
        # this is a bit weird because I want the urls to be the same as they
        # are configured for apache, where they are all starting with /api

        import aceapi
        from saq.database import initialize_database

        app = aceapi.create_app(testing=True)
        from werkzeug.serving import run_simple
        from werkzeug.wsgi import DispatcherMiddleware
        from flask import Flask
        app.config['DEBUG'] = True
        app.config['APPLICATION_ROOT'] = '/api'
        application = DispatcherMiddleware(Flask('dummy_app'), {
            app.config['APPLICATION_ROOT']: app,
        })

        if listen_address is None:
            listen_address = saq.CONFIG.get('api', 'listen_address')
        if listen_port is None:
            listen_port = saq.CONFIG.getint('api', 'listen_port')
        ssl_context = (saq.CONFIG.get('api', 'ssl_cert') if ssl_cert is None
                       else ssl_cert, saq.CONFIG.get('api', 'ssl_key')
                       if ssl_key is None else ssl_key)

        initialize_database()
        saq.db = aceapi.db.session

        logging.info(
            f"starting api server on {listen_address} port {listen_port}")
        run_simple(listen_address,
                   listen_port,
                   application,
                   ssl_context=ssl_context,
                   use_reloader=False)
Пример #30
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(config)

    db.init_app(app)

    security.init_app(app,
                      user_datastore,
                      confirm_register_form=ExtendedRegisterForm,
                      login_form=ExtendedLoginForm)
    security.send_mail_task(_send_mail_task)

    app.context_processor(_inject_processor)
    _inject_template_global(app)

    app.register_blueprint(index.bp, url_prefix='/')
    app.register_blueprint(account.bp, url_prefix='/')

    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {'/api': api})

    return app
Пример #31
0
    return headers


def get_user_key(service, user):
    key = user.keys.filter_by(service_alias=service.alias).first()
    if not key:
        abort(403)
    if key.is_expired():
        # Key has expired
        if key.refresh_token:
            data = service.refresh_token(key.refresh_token)
            key.update(data)
            models.db.session.add(key)
            models.db.session.commit()
        else:
            # Unable to refresh the token
            abort(403)
    return key


blog = static.Cling('blog/output')
app = DispatcherMiddleware(config.app, {
    '/blog': blog,
})


if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
Пример #32
0
from werkzeug.wsgi import DispatcherMiddleware
from prj import app as pwaa
from gt_app import app as gtapp
from werkzeug.serving import run_simple


application = DispatcherMiddleware(pwaa, {
    '/gtapp':     gtapp
})


# When it runs standalone in development
if __name__ == "__main__":
    application.debug = True
    run_simple('0.0.0.0', 5000, application, use_reloader=True)
Пример #33
0
from etd import app
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple

def simple(env, resp):
    resp(b'200 OK', [('Content-Type', b'text/plain')])
    return [b'CCETD World']

parent_app = DispatcherMiddleware(
    simple, 
    {"/etd": app})

if app.config.get("DEBUG") is True:
    parent_app.debug = True

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8084, debug=True)
#     run_simple('0.0.0.0', 8095, parent_app, use_reloader=True, use_debugger=True)
Пример #34
0
http://www.onurguzel.com/
how-to-run-flask-applications-with-nginx-using-gunicorn/
"""

import argparse
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.contrib.fixers import ProxyFix
from quokka import create_app, create_api
from quokka.utils.paas import activate

# If running on PAAS such as OpenShift or heroku may require venv activation
activate()

application = DispatcherMiddleware(create_app(), {
    '/api': create_api()
})

application.wsgi_app = ProxyFix(application.app.wsgi_app)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run Quokka App for WSGI")
    parser.add_argument('-p', '--port', help='App Port')
    parser.add_argument('-i', '--host', help='App Host')
    parser.add_argument('-r', '--reloader', action='store_true',
                        help='Turn reloader on')
    parser.add_argument('-d', '--debug', action='store_true',
                        help='Turn debug on')
    args = parser.parse_args()
    run_simple(
        args.host or '0.0.0.0',