Esempio n. 1
0
def parse_sparse_fields_params(request: Request) -> Dict[str, List[str]]:
    """
    Parses a request's ``fields`` query parameter, if present,
    and returns a dictionary of resource type -> sparse fields.

    Example:

    .. code-block:: python

        # request URL: /articles/?fields[articles]=title,content
        assert parse_sparse_fields_params(request) == {'articles': ['title', 'content']}
    """
    sparse_fields = dict()
    for qp_name, qp_value in request.query_params.items():
        if qp_name.startswith('fields[') and qp_name.endswith(']'):
            resource_name_start = qp_name.index('[') + 1
            resource_name_end = qp_name.index(']')
            resource_name = qp_name[resource_name_start:resource_name_end]
            if not resource_name or not qp_value or not all(
                    qp_value.split(',')):
                raise JSONAPIException(
                    status_code=400, detail='Incorrect sparse fields request.')

            sparse_fields[resource_name] = qp_value.split(',')
    return sparse_fields
Esempio n. 2
0
def parse_sparse_fields_params(request: Request) -> Dict[str, List[str]]:
    """
    Parses a request's `fields` query parameter, if present,
    and returns a dictionary of resource type -> sparse fields.

    For example, if a request were to reach
        `/some-resource/?fields[some-resource]=foo,bar`
    then:
        `parse_sparse_fields_params(request) == {'some-resource': ['foo', 'bar']}`
    """
    sparse_fields = dict()
    for qp_name, qp_value in request.query_params.items():
        if qp_name.startswith('fields[') and qp_name.endswith(']'):
            resource_name_start = qp_name.index('[') + 1
            resource_name_end = qp_name.index(']')
            resource_name = qp_name[resource_name_start:resource_name_end]
            if not resource_name or not qp_value or not all(
                    qp_value.split(',')):
                raise JSONAPIException(
                    status_code=400, detail='Incorrect sparse fields request.')

            sparse_fields[resource_name] = qp_value.split(',')
    return sparse_fields