Filter handlers that provide an acceptable mime-type.

    Finds the best match among handlers given an Accept header, and returns
    those handlers that provide the matching mime-type.

def negotiate_accept(accept, handlers):
    """Filter handlers that provide an acceptable mime-type.

    Finds the best match among handlers given an Accept header, and returns
    those handlers that provide the matching mime-type.
    """
    provided = [h.provides for h in handlers]
    if None in provided:
        # Not all handlers are annotated - disable content-negotiation
        # for Accept.
        # TODO: We could implement an "optimistic mode": If a fully qualified
        # mime-type was requested and we have a specific handler that provides
        # it, choose that handler instead of the default handler (depending on
        # 'q' value).
        return [h for h in handlers if h.provides is None]
    else:
        # All handlers are annotated with the mime-type they
        # provide: find the best match.
        #
        # mimeparse.best_match expects the supported mime-types to be sorted
        # in order of increasing desirability. By default, we use the order in
        # which handlers were added (earlier means better).
        # TODO: add "priority" parameter for user-defined priorities.
        best_match = mimeparse.best_match(reversed(provided), accept)
        return [h for h in handlers if h.provides == best_match]