|  | 
|  | 1 | +import logging | 
|  | 2 | + | 
|  | 3 | +from connexion import FlaskApp | 
|  | 4 | +from connexion.lifecycle import ConnexionRequest, ConnexionResponse | 
|  | 5 | +from connexion.problem import problem | 
|  | 6 | + | 
|  | 7 | +logger = logging.getLogger(__name__) | 
|  | 8 | + | 
|  | 9 | + | 
|  | 10 | +async def handle_error(request: ConnexionRequest, ex: Exception) -> ConnexionResponse: | 
|  | 11 | +    """ | 
|  | 12 | +    Report an error that happened while processing a request. | 
|  | 13 | +    See: https://connexion.readthedocs.io/en/latest/exceptions.html | 
|  | 14 | +
 | 
|  | 15 | +    This function is defined as `async` so it can be called by the | 
|  | 16 | +    Connexion asynchronous middleware framework without a wrapper. | 
|  | 17 | +    If a plain function is provided, the framework calls the function | 
|  | 18 | +    from a threadpool and the exception stack trace is not available. | 
|  | 19 | +
 | 
|  | 20 | +    :param request: Request that failed | 
|  | 21 | +    :parm ex: Exception that was raised | 
|  | 22 | +    :return: ConnexionResponse with RFC7087 problem details | 
|  | 23 | +    """ | 
|  | 24 | +    # log the request URL, exception and stack trace | 
|  | 25 | +    logger.exception("Request to %s caused exception", request.url) | 
|  | 26 | +    return problem(title="Error", status=500, detail=repr(ex)) | 
|  | 27 | + | 
|  | 28 | + | 
|  | 29 | +def create_app() -> FlaskApp: | 
|  | 30 | +    """ | 
|  | 31 | +    Create the Connexion FlaskApp, which wraps a Flask app. | 
|  | 32 | +
 | 
|  | 33 | +    :return Newly created FlaskApp | 
|  | 34 | +    """ | 
|  | 35 | +    app = FlaskApp(__name__, specification_dir="spec/") | 
|  | 36 | +    # hook the functions to the OpenAPI spec | 
|  | 37 | +    title = {"title": "Hello World Plus Example"} | 
|  | 38 | +    app.add_api("openapi.yaml", arguments=title, validate_responses=True) | 
|  | 39 | +    app.add_api("swagger.yaml", arguments=title, validate_responses=True) | 
|  | 40 | +    # hook an async function that is invoked on any exception | 
|  | 41 | +    app.add_error_handler(Exception, handle_error) | 
|  | 42 | +    # return the fully initialized FlaskApp | 
|  | 43 | +    return app | 
|  | 44 | + | 
|  | 45 | + | 
|  | 46 | +# create and publish for import by other modules | 
|  | 47 | +conn_app = create_app() | 
0 commit comments