예제 #1
0
파일: request.py 프로젝트: jeffrey4l/falcon
    def get_param_as_bool(self, name, required=False, store=None):
        """Return the value of a query string parameter as a boolean

        The following bool-like strings are supported::

            TRUE_STRINGS = ('true', 'True', 'yes')
            FALSE_STRINGS = ('false', 'False', 'no')

        Args:
            name (str): Parameter name, case-sensitive (e.g., 'limit')
            required (bool, optional): Set to True to raise HTTPBadRequest
                instead of returning gracefully when the parameter is not
                found or is not a recognized bool-ish string (default False).
            store (dict, optional): A dict-like object in which to place the
                value of the param, but only if the param is found (default
                *None*).

        Returns:
            bool: The value of the param if it is found and can be converted
            to a boolean. If the param is not found, returns *None* unless
            required is True.

        Raises
            HTTPBadRequest: The param was not found in the request, even though
                it was required to be there.

        """

        params = self._params

        # PERF: Use if..in since it is a good all-around performer; we don't
        #       know how likely params are to be specified by clients.
        if name in params:
            val = params[name]
            if val in TRUE_STRINGS:
                val = True
            elif val in FALSE_STRINGS:
                val = False
            else:
                msg = 'The value of the parameter must be "true" or "false".'
                raise InvalidParam(msg, name)

            if store is not None:
                store[name] = val

            return val

        if not required:
            return None

        description = 'The "' + name + '" query parameter is required.'
        raise HTTPBadRequest('Missing query parameter', description)
예제 #2
0
파일: request.py 프로젝트: jeffrey4l/falcon
    def get_param_as_list(self,
                          name,
                          transform=None,
                          required=False,
                          store=None):
        """Return the value of a query string parameter as a list.

        Note that list items must be comma-separated.

        Args:
            name (str): Parameter name, case-sensitive (e.g., 'limit')
            transform (callable, optional): An optional transform function
                that takes as input each element in the list as a string and
                outputs a transformed element for inclusion in the list that
                will be returned. For example, passing the int function will
                transform list items into numbers.
            required (bool, optional): Set to True to raise HTTPBadRequest
                instead of returning gracefully when the parameter is not
                found or is not an integer (default False)
            store (dict, optional): A dict-like object in which to place the
                value of the param, but only if the param is found (default
                *None*).

        Returns:
            list: The value of the param if it is found. Otherwise, returns
            *None* unless required is True. for partial lists, *None* will be
            returned as a placeholder. For example::

                things=1,,3

            would be returned as::

                ['1', None, '3']

            while this::

                things=,,,

            would just be retured as::

                [None, None, None, None]

        Raises
            HTTPBadRequest: The param was not found in the request, but was
                required.
        """

        params = self._params

        # PERF: Use if..in since it is a good all-around performer; we don't
        #       know how likely params are to be specified by clients.
        if name in params:
            items = params[name].split(',')

            # PERF(kgriffs): Use if-else rather than a DRY approach
            # that sets transform to a passthrough function; avoids
            # function calling overhead.
            if transform is None:
                items = [i if i != '' else None for i in items]
            else:
                try:
                    items = [transform(i) if i != '' else None for i in items]
                except ValueError:
                    msg = 'The value is not formatted correctly.'
                    raise InvalidParam(msg, name)

            if store is not None:
                store[name] = items

            return items

        if not required:
            return None

        raise HTTPBadRequest('Missing query parameter',
                             'The "' + name + '" query parameter is required.')
예제 #3
0
파일: request.py 프로젝트: jeffrey4l/falcon
    def get_param_as_int(self,
                         name,
                         required=False,
                         min=None,
                         max=None,
                         store=None):
        """Return the value of a query string parameter as an int.

        Args:
            name (str): Parameter name, case-sensitive (e.g., 'limit')
            required (bool, optional): Set to True to raise HTTPBadRequest
                instead of returning gracefully when the parameter is not
                found or is not an integer (default False).
            min (int, optional): Set to the minimum value allowed for this
                param. If the param is found and it is less than min, an
                HTTPError is raised.
            max (int, optional): Set to the maximum value allowed for this
                param. If the param is found and its value is greater than
                max, an HTTPError is raised.
            store (dict, optional): A dict-like object in which to place the
                value of the param, but only if the param is found (default
                *None*).

        Returns:
            int: The value of the param if it is found and can be converted to
                an integer. If the param is not found, returns *None*, unless
                ``required`` is True.

        Raises
            HTTPBadRequest: The param was not found in the request, even though
                it was required to be there. Also raised if the param's value
                falls outside the given interval, i.e., the value must be in
                the interval: min <= value <= max to avoid triggering an error.

        """

        params = self._params

        # PERF: Use if..in since it is a good all-around performer; we don't
        #       know how likely params are to be specified by clients.
        if name in params:
            val = params[name]
            try:
                val = int(val)
            except ValueError:
                msg = 'The value must be an integer.'
                raise InvalidParam(msg, name)

            if min is not None and val < min:
                msg = 'The value must be at least ' + str(min)
                raise InvalidParam(msg, name)

            if max is not None and max < val:
                msg = 'The value may not exceed ' + str(max)
                raise InvalidParam(msg, name)

            if store is not None:
                store[name] = val

            return val

        if not required:
            return None

        description = 'The "' + name + '" query parameter is required.'
        raise HTTPBadRequest('Missing query parameter', description)