Flask-RESTPlus similar resources for MongoEngine model

Suppose there are several similar MongoEngine models and there is a need to modify them through REST. Here is an example how to create a set of such similar resources.

model1_api = Namespace('model-1', description='My first model')
model2_api = Namespace('model-2', description='My second model')

def my_model_resource(my_model, api):

    @api.doc(params={'id': 'A {} Id'.format(my_model.__name__)})
    class MyModelResource(Resource):
        model = my_model

        def get_object(self, id, **kwargs):
            obj = self.model.objects(id=id).first()
            if not obj:
                abort(404)
            return obj

        @add_doc('Get the {} by id'.format(model.__name__))
        def get(self, id, **kwargs):
            return self.get_object(id, **kwargs).to_dict()

        def delete(self, id, **kwargs):
            """Delete object by id"""
            self.get_object(id, **kwargs).delete()
            return {}, 204

        @api.response(200, '{} updated'.format(model.__name__))
        @add_doc('Update the {}'.format(model.__name__))
        def put(self, id, **kwargs):
            data = request.get_json()
            obj = self.get_object(id, **kwargs)
            obj.update(**data)
            return self.get(id, **kwargs)

    return MyModelResource

for model, api in {Model1: model1_api, Model2: model2_api}.items():
    api.add_resource(my_resource(model, api), '/<string:id>')
comments powered by Disqus