Esempio n. 1
0
    def create(self, data):
        """Query helper for creating a row

        :param model: name of the table model
        :param fields: dict of columns:values to create
        """

        new_data = self._sanitize_for_create(data)

        if self.name in ('facts', 'attrs'):
            existing = self.api._model_query(
                self.name, 'node_id=%d and key="%s"' % (
                    int(new_data['node_id']), new_data['key']))
            if len(existing) != 0:
                return self.update(existing[0]['id'], data)

        r = self.model(**new_data)

        session.add(r)
        try:
            session.commit()
            return r.jsonify(api=self.api)
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            msg = "Unable to create %s, duplicate entry" % (self.name.title())
            raise exceptions.CreateError(msg)
        except sqlalchemy.exc.StatementError as e:
            session.rollback()
            # msg = e.message
            msg = "JSON object must be either type(dict) or type(list) " \
                  "not %s" % str(e)
            raise exceptions.CreateError(msg)
Esempio n. 2
0
    def delete(self, id):
        id = int(id)
        r = self.model.query.filter_by(id=id).first()
        # We need generate an object hash to pass to the backend notification

        try:
            session.delete(r)
            session.commit()
            return True
        except sqlalchemy.orm.exc.UnmappedInstanceError as e:
            session.rollback()
            msg = "%s id does not exist" % (self.name.title())
            raise exceptions.IdNotFound(message=msg)
        except sqlalchemy.exc.InvalidRequestError as e:
            session.rollback()
            msg = e.msg
            raise RuntimeError(msg)
Esempio n. 3
0
    def update(self, id, data):
        id = int(id)

        new_data = self._sanitize_for_update(data)
        r = self.model.query.filter_by(id=id).first()

        for field in new_data:
            r.__setattr__(field, data[field])

        try:
            ret = r.jsonify(api=self.api)
            session.commit()
            return ret
        except sqlalchemy.exc.InvalidRequestError as e:
            session.rollback()
            msg = e.msg
            raise RuntimeError(msg)
        except:
            session.rollback()
            raise