Exemplo n.º 1
0
    def common_error_handler(exception):
        """
        Generally, each route handler should be decorated with @dss_handler, which manages exceptions. The two cases
        that fail are:

        1. handlers that are not decorated.
        2. handlers that return a code that is not in the swagger spec.

        In both cases, the exception would be punted here, and we return this very generic error that also happens to
        bypass all validation.
        """
        problem = {
            'status': requests.codes.server_error,
            'code': "unhandled_exception",
            'title': str(exception),
            'stacktrace': traceback.format_exc(),
        }
        if isinstance(exception, (OAuthProblem, OAuthResponseProblem,
                                  OAuthScopeProblem, Forbidden)):
            problem['status'] = exception.code
            problem['code'] = exception.__class__.__name__
            problem['title'] = exception.description
        return FlaskApi.get_response(
            ConnexionResponse(
                status_code=problem['status'],
                mimetype="application/problem+json",
                content_type="application/problem+json",
                body=problem,
            ))
Exemplo n.º 2
0
        def _make_response(response):
            from connexion.apis.flask_api import FlaskApi

            mimetype = default_mimetype
            if hasattr(request, 'prom_connexion_content_type'):
                mimetype = request.prom_connexion_content_type

            return FlaskApi.get_response(response, mimetype=mimetype)
Exemplo n.º 3
0
def error_method_not_allowed(exception):
    return FlaskApi.get_response(
        problem(
            status=exception.code,
            title="Invalid input",
            detail=exception.description,
            headers={"Allow": "POST"},
        ))
Exemplo n.º 4
0
    def example_resolver(self, operation):
        linked_responses = []

        consumes = operation.consumes
        request = FlaskApi.get_request()

        if all_json(consumes):
            request_body = request.json
        elif consumes[0] in FORM_CONTENT_TYPES:
            request_body = {sanitized(k): v for k, v in request.form.items()}
        else:
            request_body = request.body

        try:
            query = request.query.to_dict(flat=False)
        except AttributeError:
            query = dict(request.query.items())

        content_type_header = request.headers.get('Content-Type')
        content_type_header = content_type_header or request.headers.get(
            'Accept', '*/*')
        content_type_header = strip_charset(content_type_header)

        # first priority - Request body
        if request_body:
            try:
                operation_request_body = operation.request_body['content'][
                    content_type_header]
                for item in operation_request_body.get('x-link-response'):
                    if dict(item.get('value')) == request_body:
                        linked_responses.append(item.get('x-response-id'))
            except KeyError:
                pass

        # second priority - Query params
        if query:
            query_params = filter(lambda x: x.get('in') == 'query',
                                  operation.parameters)
            for param in query_params:
                param_val = query.get(param.get('name'), None)
                if param_val is not None:
                    for item in param.get('x-link-response'):
                        if item.get('value') in param_val:
                            linked_responses.append(item.get('x-response-id'))

        # third priority - Headers
        if content_type_header:
            header_params = filter(lambda x: x.get('in') == 'header',
                                   operation.parameters)
            for param in header_params:
                if param.get('name').lower() in ['accept', 'content-type']:
                    for item in param.get('x-link-response'):
                        if item.get('value') == content_type_header:
                            linked_responses.append(item.get('x-response-id'))

        return linked_responses
Exemplo n.º 5
0
    def register(
            self,
            specification,
            base_path=None,
            arguments=None,
            validate_responses=True,
            strict_validation=True,
            resolver=None,
            auth_all_paths=False,
            debug=False,
            resolver_error_handler=None,
            validator_map=None,
            pythonic_params=False,
            pass_context_arg_name=None,
            options=dict(swagger_url="apidocs"),
    ):
        """Adds an API to the application based on a swagger file
        """

        app = self.__app

        logger.debug(f"Adding API: {specification}")

        self.__api = api = FlaskApi(
            specification=pathlib.Path(specification),
            base_path=base_path,
            arguments=arguments,
            validate_responses=validate_responses,
            strict_validation=strict_validation,
            resolver=resolver,
            auth_all_paths=auth_all_paths,
            debug=app.debug,
            resolver_error_handler=resolver_error_handler,
            validator_map=validator_map,
            pythonic_params=pythonic_params,
            pass_context_arg_name=pass_context_arg_name,
            options=options,
        )
        self.swagger_url = api.options.openapi_console_ui_path
        app.register_blueprint(api.blueprint)

        return api
Exemplo n.º 6
0
def common_error_handler(exception=None):
    """
    :type exception: Exception
    """
    if isinstance(exception, ProblemException):
        response = problem(
            status=exception.status,
            title=exception.title,
            detail=exception.detail,
            type=exception.type,
            instance=exception.instance,
            headers=exception.headers,
            ext=exception.ext,
        )
    else:
        if not isinstance(exception, HTTPException):
            exception = InternalServerError()

        response = problem(title=exception.name, detail=exception.description, status=exception.code, headers=exception.get_headers())

    return FlaskApi.get_response(response)
Exemplo n.º 7
0
        def wrapper(request):
            try:
                return origwrapper(request)
            except DSSBindingException as ex:
                status = ex.status
                code = ex.code
                title = ex.message
                stacktrace = traceback.format_exc()

                return FlaskApi.get_response(
                    ConnexionResponse(
                        status_code=status,
                        mimetype="application/problem+json",
                        content_type="application/problem+json",
                        body={
                            'status': status,
                            'code': code,
                            'title': title,
                            'stacktrace': stacktrace,
                        },
                    ))
Exemplo n.º 8
0
    def handle_offer_mgr_exception(exc) -> flask.Response:
        response = connexion.problem(status=400, title=exc.message, detail=exc.detail)

        return FlaskApi.get_response(response)
Exemplo n.º 9
0
 def verify_request_flask(self) -> Optional[Response]:
     """Verify request with token authentication and return a flask compatible response"""
     res = self.verify_request()
     if res:
         return FlaskApi.get_response(res)
     return None