Python connexion.App() Examples

The following are 17 code examples of connexion.App(). 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 connexion , or try the search function .
Example #1
Source File: __main__.py    From video-analytics-serving with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def main(options):
    try:
        app = connexion.App(__name__, specification_dir='rest_api/')
        app.add_api('video-analytics-serving.yaml',
                    arguments={'title': 'Video Analytics Serving API'})
        logger.info("Starting Tornado Server on port: %s", options.port)
        app.run(server='tornado', port=options.port)
    except Exception as error:
        logger.error("Error Starting Tornado Server") 
Example #2
Source File: app.py    From vmaas with GNU General Public License v2.0 6 votes vote down vote up
def create_app():
    """ Creates the application for webapp utils. """
    utils_app = connexion.App("webapp-utils", options={'swagger_ui': True,
                                                       'openapi_spec_path': '/openapi.json'})
    utils_app.add_api(SPEC,
                      resolver=RestyResolver('app'),
                      validate_responses=True,
                      strict_validation=True,
                      base_path='/api')

    @utils_app.app.after_request
    def set_default_headers(response): # pylint: disable=unused-variable
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type, Access-Control-Allow-Headers, \
            Authorization, X-Requested-With, x-rh-identity"
        response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS, PATCH, POST"

        return response

    return utils_app 
Example #3
Source File: test_server.py    From rbb_core with MIT License 6 votes vote down vote up
def construct_test_server():
    # Setup the API Server
    app = connexion.App(__name__, specification_dir='./../../src/rbb_swagger_server/swagger/')
    app.app.json_encoder = JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'API to access the Rosbag Bazaar service'})

    # Setup link to the database and create new schema with fake data
    rbb_server_test.database.setup_database_for_test()

    # Enable debug
    app.app.config.from_object(TestConfig)

    @app.app.teardown_appcontext
    def shutdown_session(exception=None):
        Database.get_session().remove()

    # Allow requests from everywhere
    CORS(app.app)

    return app 
Example #4
Source File: service_utils.py    From whitenoise-system with MIT License 6 votes vote down vote up
def run_app(name, spec_file, port, debug_mode=True, run_in_background=False):
    import connexion
    specification_dir = os.path.join(root_url, "service")
    sys.path.insert(0, specification_dir)

    # Create the application instance
    app = connexion.App(__name__, specification_dir=specification_dir)

    # Read the open api .yml file to configure the endpoints
    # TODO allow for specifying multiple swagger files
    app.add_api(os.path.join(root_url, "openapi", spec_file))

    app.run(host='0.0.0.0', port=port, debug=debug_mode)

    port = int(os.environ.get("BURDOCK_SERVICE_PORT", port))
    return app 
Example #5
Source File: __init__.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def create_app(self):
        logging.getLogger('connexion.operation').setLevel('ERROR')
        app = connexion.App(__name__, specification_dir='../swagger/')
        app.app.json_encoder = JSONEncoder
        app.add_api('swagger.yaml')
        return app.app 
Example #6
Source File: server.py    From data-repository-service-schemas with Apache License 2.0 5 votes vote down vote up
def configure_app():
    # The model name has to match what is in
    # tools/prepare_swagger.sh controller.
    app = connexion.App(
        "ga4gh.drs.server",
        swagger_ui=True,
        swagger_json=True)
    app.add_api(SWAGGER_PATH)

    CORS(app.app)
    return app 
Example #7
Source File: __main__.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def main():
    app = connexion.App(__name__, specification_dir='./swagger/')
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'APIs for CentOS Community Container Pipeline Service'})
    app.run(port=8080) 
Example #8
Source File: test_swagger-tester.py    From swagger-tester with MIT License 5 votes vote down vote up
def run(self):
        self.conn = connexion.App(
            'tests',
            debug=True,
            specification_dir=os.path.dirname(__file__)
        )
        self.conn.add_api('swagger.yaml')
        self.conn.app.run(port=8080) 
Example #9
Source File: __init__.py    From rbb_core with MIT License 5 votes vote down vote up
def create_app(self):
        logging.getLogger('connexion.operation').setLevel('ERROR')
        app = connexion.App(__name__, specification_dir='../swagger/')
        app.app.json_encoder = JSONEncoder
        app.add_api('swagger.yaml')
        return app.app 
Example #10
Source File: __main__.py    From rbb_core with MIT License 5 votes vote down vote up
def main():
    app = connexion.App(__name__, specification_dir='./swagger/')
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'Rosbag Bazaar API'})
    app.run(port=8080) 
Example #11
Source File: build.py    From code-coverage with Mozilla Public License 2.0 5 votes vote down vote up
def build_flask_app(project_name, app_name, openapi):
    """
    Create a new Flask backend application
    app_name is the Python application name, used as Flask import_name
    project_name is a "nice" name, used to identify the application
    """
    assert os.path.exists(openapi), "Missing openapi file {}".format(openapi)
    logger.debug("Initializing", app=app_name, openapi=openapi)

    # Start OpenAPI app
    app = connexion.App(import_name=app_name)
    app.name = project_name
    app.add_api(openapi)

    # Enable security
    security = flask_talisman.Talisman()
    security.init_app(app.app, **TALISMAN_CONFIG)

    # Enable wildcard CORS
    cors = flask_cors.CORS()
    cors.init_app(app.app, origins=["*"])

    # Add exception Json renderer
    for code, exception in werkzeug.exceptions.default_exceptions.items():
        app.app.register_error_handler(exception, handle_default_exceptions)

    # Redirect root to API
    app.add_url_rule(
        "/", "root", lambda: flask.redirect(app.options.openapi_console_ui_path)
    )

    # Dockerflow checks
    app.add_url_rule("/__heartbeat__", view_func=heartbeat_response)
    app.add_url_rule("/__lbheartbeat__", view_func=lbheartbeat_response)
    app.add_url_rule("/__version__", view_func=get_version)

    logger.debug("Initialized", app=app.name)
    return app 
Example #12
Source File: connexion.py    From fleece with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Create a FleeceApp.

        Parameters are identical to a `connexion.App, with the exception of the
        below keyword argument.

        :param logging.Logger logger:
            A Logger instance returned by `fleece.log.get_logger()` to be used
            for capturing details about errors.

            If `logger` is None, a default logger object will be created.
        """
        logger = kwargs.pop("logger", None)
        if logger is None:
            self.logger = fleece.log.get_logger(__name__)
        else:
            self.logger = logger

        super(FleeceApp, self).__init__(*args, **kwargs)

        # Capture and log any unexpected exceptions raise by handler code:
        def error_handler(exception):
            self.logger.exception(exception)
            # A `None` return value will not modify the response.
            # It's possible to return new types of responses from an error
            # handler.
            # To do so, simply return a new `werkzeug.wrappers.Response`
            # object.

        self.add_error_handler(Exception, error_handler) 
Example #13
Source File: server.py    From cwl-airflow with Apache License 2.0 5 votes vote down vote up
def run_wes_server(args):
    app = connexion.App(__name__)
    backend = CWLAirflowBackend()
    def rs(x):
        return getattr(backend, x.split('.')[-1])
    app.add_api('openapi/swagger_configuration.yaml', resolver=Resolver(rs))
    app.run(port=args.port, host=args.host) 
Example #14
Source File: service.py    From lizzy with Apache License 2.0 5 votes vote down vote up
def setup_webapp(config: configuration.Configuration):  # pragma: no cover

    arguments = {'deployer_scope': config.deployer_scope,
                 'token_url': config.token_url}
    logger.debug('Webapp Parameters', extra=arguments)
    app = connexion.App(__name__,
                        specification_dir='swagger/',
                        arguments=arguments,
                        auth_all_paths=True)
    app.add_api('lizzy.yaml')

    flask_app = app.app
    flask_app.json_encoder = JSONEncoder

    flask_app.register_error_handler(werkzeug.exceptions.NotFound,
                                     not_found_path_handler)

    flask_app.add_url_rule('/.well-known/schema-discovery',
                           'schema_discovery_endpoint',
                           expose_api_schema)

    flask_app.add_url_rule('/health',
                           'health_check_endpoint',
                           health_check)

    return app 
Example #15
Source File: init_views.py    From airflow with Apache License 2.0 5 votes vote down vote up
def init_api_connexion(app: Flask) -> None:
    """Initialize Stable API"""
    spec_dir = path.join(ROOT_APP_DIR, 'api_connexion', 'openapi')
    connexion_app = connexion.App(__name__, specification_dir=spec_dir, skip_error_handlers=True)
    connexion_app.app = app
    api_bp = connexion_app.add_api(
        specification='v1.yaml', base_path='/api/v1', validate_responses=True, strict_validation=True
    ).blueprint
    app.register_error_handler(ProblemException, connexion_app.common_error_handler)
    app.extensions['csrf'].exempt(api_bp) 
Example #16
Source File: reposcan.py    From vmaas with GNU General Public License v2.0 4 votes vote down vote up
def create_app():
    """Create reposcan app."""

    init_logging()
    LOGGER.info("Starting (version %s).", VMAAS_VERSION)
    sync_interval = int(os.getenv('REPOSCAN_SYNC_INTERVAL_MINUTES', "360")) * 60000
    if sync_interval > 0:
        PeriodicCallback(periodic_sync, sync_interval).start()
    else:
        LOGGER.info("Periodic syncing disabled.")

    ws_handler = ReposcanWebsocket()

    def terminate(*_):
        """Trigger shutdown."""
        LOGGER.info("Signal received, stopping application.")
        # Kill asyncio ioloop
        IOLoop.instance().add_callback_from_signal(ws_handler.stop)
        # Kill background pool
        SyncTask.cancel()

    for sig in KILL_SIGNALS:
        signal.signal(sig, terminate)

    ws_handler.websocket_reconnect()
    ws_handler.reconnect_callback = PeriodicCallback(ws_handler.websocket_reconnect,
                                                     WEBSOCKET_RECONNECT_INTERVAL * 1000)
    ws_handler.reconnect_callback.start()

    with open('reposcan.spec.yaml', 'rb') as specfile:
        SPEC = yaml.safe_load(specfile)  # pylint: disable=invalid-name
    SPEC['info']['version'] = VMAAS_VERSION

    app = connexion.App(__name__, options={
        'swagger_ui': True,
        'openapi_spec_path': '/openapi.json'
    })

    # Response validation is disabled due to returing streamed response in GET /pkgtree
    # https://github.com/zalando/connexion/pull/467 should fix it
    app.add_api(SPEC, resolver=connexion.RestyResolver('reposcan'),
                validate_responses=False,
                strict_validation=True,
                base_path='/api'
                )

    @app.app.route('/metrics', methods=['GET'])
    def metrics():  # pylint: disable=unused-variable
        # /metrics API shouldn't be visible in the API documentation,
        # hence it's added here in the create_app step
        return generate_latest(), 200, {'Content-Type': 'text/plain; charset=utf-8'}

    @app.app.after_request
    def set_headers(response):  # pylint: disable=unused-variable
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"
        return response

    return app 
Example #17
Source File: swagger.py    From pyms with GNU General Public License v3.0 4 votes vote down vote up
def init_app(self, config, path):
        """
        Initialize Connexion App. See more info in [Connexion Github](https://github.com/zalando/connexion)
        :param config: The Flask configuration defined in the config.yaml:
        ```yaml
        pyms:
          services:
            requests: true
            swagger:
              path: ""
              file: "swagger.yaml"
          config: <!--
            DEBUG: true
            TESTING: false
            APP_NAME: "Python Microservice"
            APPLICATION_ROOT: ""
        ```
        :param path: The current path where is instantiated Microservice class:
        ```
        Microservice(path=__file__)
                     ^^^^--- This param
        ```
        :return: Flask
        """
        check_package_exists("connexion")
        specification_dir = self.path
        application_root = self._get_application_root(config)
        if not os.path.isabs(self.path):
            specification_dir = os.path.join(path, self.path)

        app = connexion.App(__name__,
                            specification_dir=specification_dir,
                            resolver=RestyResolver(self.project_dir))

        params = {
            "specification": get_bundled_specs(
                Path(os.path.join(specification_dir, self.file))) if prance else self.file,
            "arguments": {'title': config.APP_NAME},
            "base_path": application_root,
            "options": {"swagger_url": self.url},
        }

        # Fix Connexion issue https://github.com/zalando/connexion/issues/1135
        if application_root == "/":
            del params["base_path"]

        app.add_api(**params)
        # Invert the objects, instead connexion with a Flask object, a Flask object with
        application = app.app
        application.connexion_app = app
        return application