Beispiel #1
0
def patch_api(api: Api):
    """ Wrap flask-restplus swagger decorator calls with functions that will convert Marshmallow Schemas to flask-restplus
        Model objects before passing on the Model to the wrapped function
    """
    api._restplus_expect = api.expect

    def expect_patch(self, *inputs, **kwargs):
        """ Reroute Api.expect() function to use the schema converter if provided object is a Marshmallow Schema"""
        if isinstance(self, Schema) or isinstance(self, SchemaMeta):
            model = convert_schema_to_model(api, self, self.__class__.__name__)
            inputs = list(inputs)[0] = model
        return api._restplus_expect(self, *inputs, **kwargs)

    api.expect = expect_patch

    api._restplus_response = api.response

    def response_patch(self, *args, model=None, **kwargs):
        """ Reroute Api.patch() function to use the schema -> model converter"""
        restplus_model = convert_schema_to_model(api, model, model.__class__.__name__)
        return api._restplus_response(self, *args, model=restplus_model, **kwargs)

    api.response = response_patch

    def register_method_parameters(self, method, matching_args: Union[dict, list]):
        """ Provides a way to call the function wrapped by Api.param with a list of parameters.  This allows user to
            use their Model or Schema's .keys() attribute directly in a call to register_method_parameters, and have all
            parameters registered at once instead of having to call @api.param() on every parameter.

            Collection passed to this function can be a list of parameter names, or a dict of parameter names as keys
            and descriptions as values.
        """
        if isinstance(matching_args, dict):
            for name, description in matching_args.items():
                param_wrapper = self.param(name, description, _in='query')
                param_wrapper(method)
        elif isinstance(matching_args, list):
            for name in matching_args:
                param_wrapper = self.param(name, None, _in='query')
                param_wrapper(method)
        return self

    from functools import partial
    api.register_method_parameters = partial(register_method_parameters, self=api)

    return api