Python werkzeug.wsgi.DispatcherMiddleware() Examples

The following are 8 code examples of werkzeug.wsgi.DispatcherMiddleware(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module werkzeug.wsgi , or try the search function .
Example #1
Source File: app.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_app(config_object=Config):
    app = Flask(__name__.split(".")[0])
    app.config.from_object(config_object)
    app.pluggy = manager.FlaskshopPluginManager("flaskshop")
    register_extensions(app)
    load_plugins(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})

    return app 
Example #2
Source File: app.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def setup_app():
    root_app = flask.Flask('cloudkitty')
    root_api = flask_restful.Api(root_app)
    root_api.add_resource(api_root.CloudkittyAPIRoot, '/')

    dispatch_dict = {
        '/v1': get_v1_app(),
        '/v2': get_v2_app(),
    }

    # Disabling v2 api in case v1 storage is used
    if CONF.storage.version < 2:
        LOG.warning('v1 storage is used, disabling v2 API')
        dispatch_dict.pop('/v2')

    app = dispatcher.DispatcherMiddleware(root_app, dispatch_dict)
    return app 
Example #3
Source File: test.py    From ACE with Apache License 2.0 5 votes vote down vote up
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 api
        from saq.database import initialize_database

        app = api.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 = api.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) 
Example #4
Source File: flaskapp.py    From open_dnsdb with Apache License 2.0 5 votes vote down vote up
def set_wsgi_app(self, app, base_url=None):
        if base_url is None:
            base_url = self.base_url
        if base_url != "/":
            self.wsgi_app = DispatcherMiddleware(simple_404_app, {
                base_url: app
            })
        else:
            self.wsgi_app = app 
Example #5
Source File: flaskapp.py    From open_dnsdb with Apache License 2.0 5 votes vote down vote up
def set_wsgi_app(self, app, base_url=None):
        if base_url is None:
            base_url = self.base_url
        if base_url != "/":
            self.wsgi_app = DispatcherMiddleware(simple_404_app, {
                base_url: app
            })
        else:
            self.wsgi_app = app 
Example #6
Source File: app.py    From pyspider with Apache License 2.0 4 votes vote down vote up
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

        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() 
Example #7
Source File: main.py    From flux-ci with MIT License 4 votes vote down vote up
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() 
Example #8
Source File: web.py    From aliyun-exporter with Apache License 2.0 4 votes vote down vote up
def create_app(config: CollectorConfig):

    app = Flask(__name__, instance_relative_config=True)

    client = AcsClient(
        ak=config.credential['access_key_id'],
        secret=config.credential['access_key_secret'],
        region_id=config.credential['region_id']
    )

    @app.route("/")
    def projectIndex():
        req = QueryProjectMetaRequest()
        req.set_PageSize(100)
        try:
            resp = client.do_action_with_exception(req)
        except Exception as e:
            return render_template("error.html", errorMsg=e)
        data = json.loads(resp)
        return render_template("index.html", projects=data["Resources"]["Resource"])

    @app.route("/projects/<string:name>")
    def projectDetail(name):
        req = QueryMetricMetaRequest()
        req.set_PageSize(100)
        req.set_Project(name)
        try:
            resp = client.do_action_with_exception(req)
        except Exception as e:
            return render_template("error.html", errorMsg=e)
        data = json.loads(resp)
        return render_template("detail.html", metrics=data["Resources"]["Resource"], project=name)

    @app.route("/yaml/<string:name>")
    def projectYaml(name):
        req = QueryMetricMetaRequest()
        req.set_PageSize(100)
        req.set_Project(name)
        try:
            resp = client.do_action_with_exception(req)
        except Exception as e:
            return render_template("error.html", errorMsg=e)
        data = json.loads(resp)
        return render_template("yaml.html", metrics=data["Resources"]["Resource"], project=name)

    app.jinja_env.filters['formatmetric'] = format_metric
    app.jinja_env.filters['formatperiod'] = format_period

    app_dispatch = DispatcherMiddleware(app, {
        '/metrics': make_wsgi_app()
    })
    return app_dispatch