示例#1
0
文件: api.py 项目: emosyne/crate
def is_nlprp_protocol_valid(x: JsonObjectType,
                            min_version: Version = None,
                            max_version: Version = None) -> bool:
    """
    Is the parameter a valid NLPRP request/response object?

    Args:
        x: dictionary to test
        min_version: minimum NLPRP version to accept; None for no minimum
        max_version: maximum NLPRP version to accept; None for no maximum
    """
    try:
        protocol = x.get(NlprpKeys.PROTOCOL, None)  # type: JsonObjectType
        # ... will raise AttributeError if not a dict
        protocol_name = protocol[NlprpKeys.NAME]
        assert protocol_name.lower() == NlprpValues.NLPRP_PROTOCOL_NAME
        protocol_version = Version(protocol[NlprpKeys.VERSION])
        # ... the Version() call may raise TypeError, ValueError
        if min_version is not None:
            assert protocol_version >= min_version
        if max_version is not None:
            assert protocol_version <= max_version
    except (AssertionError, AttributeError, KeyError, TypeError, ValueError):
        return False
    return True
示例#2
0
文件: api.py 项目: emosyne/crate
def json_get_toplevel_args(nlprp_request: JsonObjectType,
                           required: bool = True) -> JsonObjectType:
    """
    Returns the top-level arguments for a NLPRP request.

    Args:
        nlprp_request: the NLPRP request object
        required: are the args required?

    Returns:
        dict: the result

    Raises:
        :exc:`NlprpError` if the value is bad, or is missing and required.
    """
    value = nlprp_request.get(NlprpKeys.ARGS)
    if value is None:
        if required:
            raise key_missing_error(NlprpKeys.ARGS, is_args=True)
        else:
            return {}  # type: JsonArrayType
    if not isinstance(value, dict):
        mkerror(
            BAD_REQUEST,
            f"{NlprpKeys.ARGS!r} parameter not a JSON object (dictionary)")
    return value
示例#3
0
文件: api.py 项目: emosyne/crate
def json_get_array_of_str(x: JsonObjectType,
                          key: str,
                          required: bool = False) -> List[str]:
    """
    Gets an array of strings from part of the JSON request.

    Args:
        x: a JSON object (dictionary)
        key: the name of the key
        required: is the array required?

    Returns:
        list: the result, or ``[]`` if the parameter is missing and
        ``required == False``.

    Raises:
        :exc:`NlprpError` if the value is bad, or is missing and required.
    """
    value = x.get(key)
    if value is None:  # missing, or "null"
        if required:
            raise key_missing_error(key)
        else:
            return []  # type: JsonArrayType
    if not isinstance(value, list):
        mkerror(BAD_REQUEST, f"{key!r} parameter not a JSON array (list)")
    if not all(isinstance(x, str) for x in value):
        mkerror(BAD_REQUEST, f"Non-string value as part of {key!r}")
    return value
示例#4
0
文件: api.py 项目: emosyne/crate
def json_get_object(x: JsonObjectType,
                    key: str,
                    required: bool = False) -> JsonObjectType:
    """
    Gets an object (dictionary) parameter from part of the JSON request.

    Args:
        x: a JSON object (dictionary)
        key: the name of the key
        required: is the object required?

    Returns:
        list: the result, or ``{}`` if the parameter is missing and
        ``required == False``.

    Raises:
        :exc:`NlprpError` if the value is bad, or is missing and required.
    """
    value = x.get(key)
    if value is None:  # missing, or "null"
        if required:
            raise key_missing_error(key)
        else:
            return {}  # type: JsonArrayType
    if not isinstance(value, dict):
        mkerror(BAD_REQUEST,
                f"{key!r} parameter not a JSON object (dictionary)")
    return value
示例#5
0
文件: api.py 项目: emosyne/crate
def json_get_str(x: JsonObjectType,
                 key: str,
                 default: str = None,
                 required: bool = False) -> str:
    """
    Gets a string parameter from part of the JSON request.

    Args:
        x: a JSON object (dictionary)
        key: the name of the key
        default: the default value
        required: is it mandatory, or can it be missing or ``null``?

    Returns:
        str: the result, or the default

    Raises:
        :exc:`NlprpError` if the value is bad, or is missing and required.
    """
    value = x.get(key, default)
    if value is None:  # missing, or "null"
        if required:
            raise key_missing_error(key)
        else:
            return default
    if not isinstance(value, str):
        mkerror(BAD_REQUEST, f"{key!r} parameter not string")
    return value