Esempio n. 1
0
    def put_collection(self, session):
        """
        Update one or multiple objects.

        Each object MUST contain its original pk value.

        """
        data_list = self.submitted_collection_data
        # Update all members in data list
        count = 0
        query = session.query(self.model)
        try:
            for data in data_list:
                pk_value = data.pop('id')
                update_query = query.filter(self.model.id == pk_value)
                update_query.update(data)
                count += 1
        except:
            LOG.exception('Error updating object(s) during PUT request')
            transaction.doom()
            return error_response(_("Object(s) update failed"))

        if not count:
            return error_response(_("No object(s) updated"))

        msg = _("Object(s) updated successfully")
        # TODO: Check support for rowcount
        # http://docs.sqlalchemy.org/en/latest/core/connections.html
        # sqlalchemy.engine.ResultProxy.rowcount
        return info_response(msg, data={'count': count})
Esempio n. 2
0
    def activities(self):
        """
        Get activities for current user.

        By default activities are getted only for current day.
        Different date range can be queried using `from` and `to`
        arguments in the request.

        Returns a List of Activity.

        """
        if not self.is_valid_object:
            raise NotFound()

        try:
            (from_date, to_date) = self.get_filter_from_to()
        except (TypeError, ValueError):
            return error_response(_('Invalid date format'))

        # When no dates are given use current date as default
        if not from_date and not to_date:
            from_date = datetime.date.today()
            to_date = from_date + datetime.timedelta(days=1)

        query = Activity.query()
        query = query.filter(Activity.user_id == self.pk_value)
        if from_date:
            query = query.filter(Activity.start >= from_date)
        if to_date:
            query = query.filter(Activity.start < to_date)

        return query.all()
Esempio n. 3
0
def handle_api_request_data_errors(err, request):
    """
    Generic error handler for request with invalid JSON data.

    """
    data = {'code': 'INVALID_JSON_DATA'}
    message = error.CODES.get(data['code'])
    return error_response(message, data=data)
Esempio n. 4
0
    def put_member(self):
        """
        Update current object data.

        """
        query = self.object.query()
        try:
            count = query.update(self.submitted_member_data)
        except colander.Invalid:
            raise
        except:
            LOG.exception('Error updating object during PUT request')
            transaction.doom()
            return error_response(_("Object update failed"))

        if not count:
            return error_response(_("No object was updated"))

        return self.object
Esempio n. 5
0
def handle_api_errors(err, request):
    """
    Generic error handler API errors.

    """
    # Add schema validation information
    data = {
        'code': err.code,
        'details': err.details,
    }
    return error_response(err.msg, data=data)
Esempio n. 6
0
def handle_schema_validation_errors(err, request):
    """
    Generic error handler for Colander data and validation errors.

    """
    # Add schema validation information
    data = {
        'code': 'VALIDATION_ERROR',
        'fields': err.asdict(),
        'details': unicode(err),
    }
    message = error.CODES.get(data['code'])
    return error_response(message, data=data)
Esempio n. 7
0
    def delete_member(self):
        """
        Delete current object from database.

        """
        serialized_object = dict(self.object)
        query = self.object.query()
        count = query.delete()
        if not count:
            return error_response(_('No object was deleted'))
        else:
            # Return the deleted object
            return serialized_object
Esempio n. 8
0
def handle_database_integrity_errors(exc, request):
    """
    Generic error handler for database IntegrityErrors.

    Traceback error message is also added to response.

    """
    # Mark current transaction to be aborted ath the end of request
    transaction.doom()
    # Add exception message to response
    details = exc.message.replace('(IntegrityError)', '')
    data = {
        'code': 'DATA_INTEGRITY_ERROR',
        'details': details.strip(),
    }
    message = error.CODES.get(data['code'])
    return error_response(message, data=data)
Esempio n. 9
0
    def post_collection(self, session):
        """
        Create new object(s).

        Request body can be a JSON object or a list of objects.

        """
        obj_list = []
        for data in self.submitted_collection_data:
            obj = self.model(**data)
            session.add(obj)
            obj_list.append(obj)

        # Flush to generate IDs
        try:
            session.flush()
        except:
            msg = "Unable to flush POST collectiond data for /%s"
            LOG.exception(msg, self.get_route_prefix())
            return error_response(_("Error creating object(s)"))

        return obj_list