コード例 #1
0
ファイル: crud.py プロジェクト: project-hypr/hypr
    def delete(self, **kwargs):
        """Delete an existing instance of the model.

        delete() acts as the DELETE of the CRUD functions. It deletes an
        existing instance of the model.

        Docs:
            Delete an existing instance of ``{model}``.

            Responses
            ---------

            **204 No Content**
        """
        model = self.__model__

        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']
        if bulk and not kwargs:
            # TODO: implement bulk PUT
            raise NotImplementedError()
        elif kwargs:
            rv = model.one(*self._uid(**kwargs)) or abort(404)
            rv.delete(commit=False)
        else:
            abort(400)

        try:
            model.commit()
        except ModelConflictException:
            model.rollback()
            abort(409)
        else:
            return '', 204
コード例 #2
0
ファイル: crud.py プロジェクト: project-hypr/hypr
    def put(self, _data=None, **kwargs):
        """Update an existing instance of the model.

        put() acts as the UPDATE of the CRUD functions. It modifies an existing
        instance of the model with the JSON payload of the request. The data
        can be validated with the help of jsonschema.

        Args:
            _data: override the payload of the request.

        Docs:
            Update an existing instance of ``{model}``.

            Request
            -------

            Headers
            =======
            The request should have the Content-Type application/json.

            Body
            ====
            The data should comply with the following schema::

                {model.schema}
        """
        model = self.__model__

        if _data is None:
            _data = yield from request.json()
        if _data is None:
            abort(400)

        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']
        if bulk and not kwargs:
            # TODO: implement bulk PUT
            raise NotImplementedError()
        elif kwargs:
            rv = model.one(*self._uid(**kwargs)) or abort(404)
            model.__validate__(_data) or abort(400)
            for k, v in _data.items():
                if hasattr(rv, k):
                    setattr(rv, k, v)
                else:
                    model.rollback()
                    abort(400)
            rv.save(commit=False)
        else:
            abort(400)

        try:
            model.commit()
        except ModelConflictException:
            model.rollback()
            abort(409)
        else:
            return rv
コード例 #3
0
ファイル: crud.py プロジェクト: pascalbertrand/hypr
    def post(self):

        model = self.__model__
        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']
        json = yield from request.json()

        if json is None:
            abort(400)

        if not model.__validate__(json):
            abort(400)

        if bulk:
            # TODO: implement bulk POST
            raise NotImplementedError()
        else:

            try:
                rv = model(**json)
            except TypeError:
                abort(400)
            else:
                rv.save(commit=False)

        # commit changes

        try:
            model.commit()
        except ModelConflictException:
            model.rollback()
            abort(409)
        else:
            return rv, 201
コード例 #4
0
ファイル: crud.py プロジェクト: pascalbertrand/hypr
    def get(self, **kwargs):

        model = self.__model__

        if len(kwargs):
            return model.one(*self._uid(**kwargs)) or abort(404)

        try:
            search, order, limit, offset, fltrs = mini_dsl(request.args)
            count = model.count(_search=search, **fltrs)
            rv = model.get(limit, offset, order, search, **fltrs)
        except ValueError:
            abort(400)
        except ModelSearchException:
            abort(400)
        else:
            return {
                'count': count,
                'result': rv,
            }
コード例 #5
0
ファイル: crud.py プロジェクト: pascalbertrand/hypr
    def delete(self, **kwargs):

        model = self.__model__
        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']

        if bulk and not kwargs:
            # TODO: implement bulk PUT
            raise NotImplementedError()
        elif kwargs:
            rv = model.one(*self._uid(**kwargs)) or abort(404)
            rv.delete(commit=False)
        else:
            abort(400)

        # commit changes

        try:
            model.commit()
        except ModelConflictException:
            model.rollback()
            abort(409)
        else:
            return '', 204
コード例 #6
0
ファイル: crud.py プロジェクト: project-hypr/hypr
    def get(self, **kwargs):
        """Return one or more instances of the model.

        get() acts as the READ of the CRUD functions. If no variable segments
        are specified, it will return a list of instances otherwise it will
        return the instance with its unique identifier defined by _uid().

        The following paragraphs are used to generate the documentation of the
        API. They can be overloaded in the docstring of inherited classes'
        methods. get() uses two special decorators for those paragraphs to
        specify whether it describes the fetch of one or multiple instances.

        @multiple
        Docs:
            Fetch a list of ``{model}`` instances.

            Request
            -------

            Query
            =====
            **Optional parameters**

                * _search: search instances for a specific value.
                * _order: sort the instances returned by the specified
                          property. Add an exclamation mark ``!`` to reverse
                          the sorting order.
                * _limit: limit the number of returned instances.
                * _offset: set an offset in the returned instances.
                * _pprint: pretty print the output.

            Any other parameter in the query string is used as a filter
            where the key is the filtering property.

        @one
        Docs:
            Fetch an instance of ``{model}``.

            Query
            =====
            **Optional parameters**

                * _pprint: pretty print the output.
        """
        model = self.__model__

        if len(kwargs):
            return model.one(*self._uid(**kwargs)) or abort(404)

        try:
            query_dsl = self._query_dsl()
            filters = self.filters()
            count = model.count(_search=query_dsl[-1], **filters)
            rv = model.get(*query_dsl, **filters)
        except ValueError:
            abort(400)
        except (ModelSearchException, ModelFilterException):
            abort(400)
        else:
            return {
                'count': count,
                'data': rv,
            }
コード例 #7
0
ファイル: crud.py プロジェクト: project-hypr/hypr
    def post(self, _data=None):
        """Create a new instance of the model.

        post() acts as the CREATE of the CRUD functions. It creates a new
        instance of the model from the JSON payload of the request. It supports
        bulk insert along with single instance creation and the data can be
        validated with the help of jsonschema.

        Args:
            _data: override the payload of the request.

        Docs:
            Create a new instance of ``{model}``.

            Request
            -------

            Headers
            =======
            The request should have the Content-Type application/json.

            Body
            ====
            The data should comply with the following schema::

                {model.schema}

            Responses
            ---------

                **201 Created**
        """
        model = self.__model__

        if _data is None:
            _data = yield from request.json()
        if _data is None:
            abort(400)

        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']
        if bulk:
            # TODO: implement bulk POST
            raise NotImplementedError()
        else:
            model.__validate__(_data) or abort(400)
            try:
                rv = model(**_data)
            except TypeError:
                abort(400)
            else:
                rv.save(commit=False)

        # commit changes and rollback on error.
        try:
            model.commit()
        except ModelConflictException as e:
            model.rollback()
            request.app.logger.debug(e.msg)
            abort(409)
        else:
            return rv, 201
コード例 #8
0
ファイル: crud.py プロジェクト: pascalbertrand/hypr
    def put(self, **kwargs):

        model = self.__model__
        bulk = request.args.get('_bulk', '').lower() in ['true', 'on', '1']
        json = yield from request.json()

        if json is None:
            abort(400)

        if not model.__validate__(json):
            abort(400)

        if bulk and not kwargs:
            # TODO: implement bulk PUT
            raise NotImplementedError()

        elif kwargs:

            rv = model.one(*self._uid(**kwargs)) or abort(404)

            for k, v in json.items():
                if hasattr(rv, k):
                    setattr(rv, k, v)
                else:
                    model.rollback()
                    abort(400)

            rv.save(commit=False)

        else:
            abort(400)

        # commit changes

        try:
            model.commit()
        except ModelConflictException:
            model.rollback()
            abort(409)
        else:
            return rv