Python connexion.FlaskApp() Examples

The following are 7 code examples of connexion.FlaskApp(). 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: run.py    From articles with MIT License 6 votes vote down vote up
def create_app():
    if "SPEC_PATH" in os.environ:
        openapi_path = os.environ["SPEC_PATH"]
    else:
        abs_file_path = os.path.abspath(os.path.dirname(__file__))
        openapi_path = os.path.join(abs_file_path, "../", "../", "openapi")
    app = connexion.FlaskApp(
        __name__,
        specification_dir=openapi_path,
        options={"swagger_ui": False, "serve_spec": False},
    )
    app.add_api("specification.yml", strict_validation=True)
    flask_app = app.app
    flask_app.json_encoder = encoder.JSONEncoder

    return flask_app 
Example #2
Source File: run.py    From articles with MIT License 5 votes vote down vote up
def create_app():
    abs_file_path = os.path.abspath(os.path.dirname(__file__))
    openapi_path = os.path.join(abs_file_path, "../", "../", "openapi")
    app = connexion.FlaskApp(
        __name__, specification_dir=openapi_path, options={"swagger_ui": False, "serve_spec": False}
    )
    app.add_api("specification.yml", strict_validation=True)
    flask_app = app.app
    flask_app.json_encoder = encoder.JSONEncoder

    return flask_app 
Example #3
Source File: hello.py    From json-logging-python with Apache License 2.0 5 votes vote down vote up
def create():
    app = connexion.FlaskApp(__name__, port=9090, specification_dir='openapi/')
    json_logging.init_connexion(enable_json=True)
    json_logging.init_request_instrument(app)

    app.add_api('helloworld-api.yaml', arguments={'title': 'Hello World Example'})
    return app 
Example #4
Source File: APIServer.py    From TensorHive with Apache License 2.0 5 votes vote down vote up
def run_forever(self):
        app = connexion.FlaskApp(__name__)
        init_jwt(app.app)

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

        app.add_api(API.SPEC_FILE,
                    arguments={
                        'title': API.TITLE,
                        'version': API.VERSION,
                        'url_prefix': API.URL_PREFIX,
                        'RESPONSES': API.RESPONSES
                    },
                    resolver=connexion.RestyResolver(API.IMPL_LOCATION),
                    strict_validation=True)
        CORS(app.app)
        log.info('[⚙] Starting API server with {} backend'.format(API_SERVER.BACKEND))
        URL = 'http://{host}:{port}/{url_prefix}/ui/'.format(
            host=API.URL_HOSTNAME,
            port=API_SERVER.PORT,
            url_prefix=API.URL_PREFIX)
        log.info(green('[✔] API documentation (Swagger UI) available at: {}'.format(URL)))
        app.run(server=API_SERVER.BACKEND,
                host=API_SERVER.HOST,
                port=API_SERVER.PORT,
                debug=API_SERVER.DEBUG,
                log=APILogger) 
Example #5
Source File: service.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
def _init_wsgi_app(self, service_name, api_spec_dir=None, api_spec_file=None):
        """
        Return an initialized service with common api resource and auth config
        :return:
        """

        try:

            enable_swagger_ui = False
            if self.configuration.get('enable_swagger_ui', None) is not None:
                enable_swagger_ui = self.configuration.get('enable_swagger_ui')
            elif self.global_configuration.get('enable_swagger_ui', None) is not None:
                enable_swagger_ui = self.global_configuration.get('enable_swagger_ui')

            flask_app_options = {'swagger_ui': enable_swagger_ui}
            self._application = connexion.FlaskApp(__name__, specification_dir=api_spec_dir, options=flask_app_options)
            flask_app = self._application.app
            flask_app.url_map.strict_slashes = False

            # Ensure jsonify() calls add whitespace for nice error responses
            flask_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

            # Suppress some verbose logs in dependencies
            import logging as py_logging
            py_logging.basicConfig(level=py_logging.ERROR)

            # Initialize the authentication system
            self.init_auth()

            flask_app.before_request(self._inject_service)
            flask_app.register_error_handler(AnchoreApiError, handle_api_exception)

            metrics.init_flask_metrics(flask_app, servicename=service_name)
            self._application.add_api(Path(api_spec_file), validate_responses=self.options.get('validate-responses'))

            return self._application
        except Exception as err:
            traceback.print_exc()
            raise err 
Example #6
Source File: test_api_specs.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
def test_api_service(service):
    """
    Creates a mocked interface for each specified swagger spec and creates
    a server to ensure swagger validates fully.

    If invalid specs are detected the spec will raise `InvalidSpecification`.

    Further enhancement of this test is to make actual requests to the Apps
    generated.
    """

    port = 8081
    name = service.rsplit('/', 3)[2]
    resolver = MockResolver(mock_all='all')
    api_extra_args = {'resolver': resolver}

    options = {"serve_spec": False, "swagger_ui": False}
    app = connexion.FlaskApp(name, options=options)

    app.add_api(service,
                resolver_error=True,
                validate_responses=True,
                strict_validation=True,
                **api_extra_args)

    client = app.app.test_client()
    # potential enhancment would be to create a request like:
    #     response = client.get('/health')
    #     assert response.status_code == 200 
Example #7
Source File: __init__.py    From agents-aea with Apache License 2.0 4 votes vote down vote up
def create_app():
    """Run the flask server."""
    CUR_DIR = os.path.abspath(os.path.dirname(__file__))
    app = connexion.FlaskApp(__name__, specification_dir=CUR_DIR)
    global app_context
    app_context = AppContext()

    app_context.oef_process = None
    app_context.agent_processes = {}
    app_context.agent_tty = {}
    app_context.agent_error = {}
    app_context.ui_is_starting = False
    app_context.agents_dir = os.path.abspath(os.getcwd())
    app_context.module_dir = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), "../../"
    )

    app.add_api("aea_cli_rest.yaml")

    @app.route("/")
    def home():
        """Respond to browser URL:  localhost:5000/."""
        return flask.render_template(
            "home.html", len=len(elements), htmlElements=elements
        )

    @app.route("/static/js/home.js")
    def homejs():
        """Serve the home.js file (as it needs templating)."""
        return flask.render_template(
            "home.js", len=len(elements), htmlElements=elements
        )

    @app.route("/favicon.ico")
    def favicon():
        """Return an icon to be displayed in the browser."""
        return flask.send_from_directory(
            os.path.join(app.root_path, "static"),
            "favicon.ico",
            mimetype="image/vnd.microsoft.icon",
        )

    return app