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
import traceback from flask_restplus import Api from sqlalchemy.orm.exc import NoResultFound # from log import log from log import log api = Api(version='1', title='flask_api_example', description='flask_api_example') fun_dict = { 'resp_204': api.response(204, 'successfully updated.'), 'resp_401': api.response(401, 'token auth fail.'), 'resp_403': api.response(403, 'access forbidden.'), 'resp_404': api.response(404, 'no result found or update object not exist'), 'expect': api.expect, 'marshal1': api.marshal_with, 'marshal2': api.marshal_list_with } @api.errorhandler def default_error_handler(e): message = 'An unhandled exception occurred.' log.exception(message) if not globals()['FLASK_DEBUG']: return {'message': message}, 500