예제 #1
0
def get_checked_field(document, name, value_type):
    """Validates and retrieves a typed field from a document.

    This function attempts to look up doc[name], and raises
    appropriate HTTP errors if the field is missing or not an
    instance of the given type.

    :param document: dict-like object
    :param name: field name
    :param value_type: expected value type, or '*' to accept any type
    :raises: HTTPBadRequest if the field is missing or not an
        instance of value_type
    :returns: value obtained from doc[name]
    """

    try:
        value = document[name]
    except KeyError:
        description = _(u'Missing "{name}" field.').format(name=name)
        raise errors.HTTPBadRequestBody(description)

    if value_type == '*' or isinstance(value, value_type):
        return value

    description = _(u'The value of the "{name}" field must be a {vtype}.')
    description = description.format(name=name, vtype=value_type.__name__)
    raise errors.HTTPBadRequestBody(description)
예제 #2
0
def validate(validator, document):
    """Verifies a document against a schema.

    :param validator: a validator to use to check validity
    :type validator: jsonschema.Draft4Validator
    :param document: document to check
    :type document: dict
    :raises: wsgi_errors.HTTPBadRequestBody
    """
    try:
        validator.validate(document)
    except jsonschema.ValidationError as ex:
        raise wsgi_errors.HTTPBadRequestBody('{0}: {1}'.format(
            ex.args, ex.message))
예제 #3
0
def load(req):
    """Reads request body, raising an exception if it is not JSON.

    :param req: The request object to read from
    :type req: falcon.Request
    :return: a dictionary decoded from the JSON stream
    :rtype: dict
    :raises: wsgi_errors.HTTPBadRequestBody
    """
    try:
        return json_utils.read_json(req.stream, req.content_length)
    except (json_utils.MalformedJSON, json_utils.OverflowedJSONInteger) as ex:
        LOG.exception(ex)
        raise wsgi_errors.HTTPBadRequestBody('JSON could not be parsed.')
예제 #4
0
    def on_patch(self, request, response, project_id, pool):
        """Allows one to update a pool's weight, uri, and/or options.

        This method expects the user to submit a JSON object
        containing at least one of: 'uri', 'weight', 'options'. If
        none are found, the request is flagged as bad. There is also
        strict format checking through the use of
        jsonschema. Appropriate errors are returned in each case for
        badly formatted input.

        :returns: HTTP | 200,400
        """
        LOG.debug(u'PATCH pool - name: %s', pool)
        data = utils.load(request)

        EXPECT = ('weight', 'uri', 'options')
        if not any([(field in data) for field in EXPECT]):
            LOG.debug(u'PATCH pool, bad params')
            raise wsgi_errors.HTTPBadRequestBody(
                'One of `uri`, `weight`, or `options` needs '
                'to be specified')

        for field in EXPECT:
            utils.validate(self._validators[field], data)

        if 'uri' in data and not storage_utils.can_connect(data['uri']):
            raise wsgi_errors.HTTPBadRequestBody('cannot connect to %s' %
                                                 data['uri'])
        fields = common_utils.fields(data,
                                     EXPECT,
                                     pred=lambda v: v is not None)

        try:
            self._ctrl.update(pool, **fields)
        except errors.PoolDoesNotExist as ex:
            LOG.exception(ex)
            raise falcon.HTTPNotFound()
예제 #5
0
    def on_put(self, request, response, project_id, pool):
        """Registers a new pool. Expects the following input:

        {"weight": 100, "uri": ""}

        An options object may also be provided.

        :returns: HTTP | [201, 204]
        """
        LOG.debug(u'PUT pool - name: %s', pool)

        data = utils.load(request)
        utils.validate(self._validators['create'], data)
        if not storage_utils.can_connect(data['uri']):
            raise wsgi_errors.HTTPBadRequestBody('cannot connect to %s' %
                                                 data['uri'])
        self._ctrl.create(pool,
                          weight=data['weight'],
                          uri=data['uri'],
                          options=data.get('options', {}))
        response.status = falcon.HTTP_201
        response.location = request.path
예제 #6
0
def filter_stream(stream, len, spec=None, doctype=JSONObject):
    """Reads, deserializes, and validates a document from a stream.

    :param stream: file-like object from which to read an object or
        array of objects.
    :param len: number of bytes to read from stream
    :param spec: (Default None) Iterable describing expected fields,
        yielding tuples with the form of:

            (field_name, value_type).

        Note that value_type may either be a Python type, or the
        special string '*' to accept any type. If spec is None, the
        incoming documents will not be validated.
    :param doctype: type of document to expect; must be either
        JSONObject or JSONArray.
    :raises: HTTPBadRequest, HTTPServiceUnavailable
    :returns: A sanitized, filtered version of the document list read
        from the stream. If the document contains a list of objects,
        each object will be filtered and returned in a new list. If,
        on the other hand, the document is expected to contain a
        single object, that object will be filtered and returned as
        a single-element iterable.
    """

    if len is None:
        description = _(u'Request body can not be empty')
        raise errors.HTTPBadRequestBody(description)

    try:
        # TODO(kgriffs): read_json should stream the resulting list
        # of messages, returning a generator rather than buffering
        # everything in memory (bp/streaming-serialization).
        document = utils.read_json(stream, len)

    except utils.MalformedJSON as ex:
        LOG.debug(ex)
        description = _(u'Request body could not be parsed.')
        raise errors.HTTPBadRequestBody(description)

    except utils.OverflowedJSONInteger as ex:
        LOG.debug(ex)
        description = _(u'JSON contains integer that is too large.')
        raise errors.HTTPBadRequestBody(description)

    except Exception as ex:
        # Error while reading from the network/server
        LOG.exception(ex)
        description = _(u'Request body could not be read.')
        raise errors.HTTPServiceUnavailable(description)

    if doctype is JSONObject:
        if not isinstance(document, JSONObject):
            raise errors.HTTPDocumentTypeNotSupported()

        return (document, ) if spec is None else (filter(document, spec), )

    if doctype is JSONArray:
        if not isinstance(document, JSONArray):
            raise errors.HTTPDocumentTypeNotSupported()

        if spec is None:
            return document

        return [filter(obj, spec) for obj in document]

    raise TypeError('doctype must be either a JSONObject or JSONArray')