Attempt to confirm the returned manifest is of a given media type

    :param response: a requests.Response
    :param media_type: media_type (str), or None to confirm
        the media type cannot be guessed
487324
def manifest_is_media_type(response, media_type):
    
    try:
        received_media_type = response.headers['Content-Type']
    except KeyError:
        # Guess media type from content
        logger.debug("No Content-Type header; inspecting content")
        received_media_type = guess_manifest_media_type(response.content)
        logger.debug("guessed media type: %s", received_media_type)

    if received_media_type is None:
        return media_type is None

    # Only compare prefix as response may use +prettyjws suffix
    # which is the case for signed manifest
    response_h_prefix = received_media_type.rsplit('+', 1)[0]
    request_h_prefix = media_type.rsplit('+', 1)[0]
    return response_h_prefix == request_h_prefix
700586
def _validate_response(response):
        
        try:
            response.raise_for_status()
        except requests.RequestException:
            raise RequestException(
                code=response.status_code,
                url=response.url,
                description=response.text)
        else:
            return response
920750
public static <T> GenericResponseBuilder<T> ok(T entity, MediaType type) {
    return ok(entity).type(type);
  }
86310
async def parse_result(response, response_type=None, *, encoding="utf-8"):
    
    if response_type is None:
        ct = response.headers.get("content-type")
        if ct is None:
            cl = response.headers.get("content-length")
            if cl is None or cl == "0":
                return ""
            raise TypeError(
                "Cannot auto-detect response type "
                "due to missing Content-Type header."
            )
        main_type, sub_type, extras = parse_content_type(ct)
        if sub_type == "json":
            response_type = "json"
        elif sub_type == "x-tar":
            response_type = "tar"
        elif (main_type, sub_type) == ("text", "plain"):
            response_type = "text"
            encoding = extras.get("charset", encoding)
        else:
            raise TypeError("Unrecognized response type: {ct}".format(ct=ct))
    if "tar" == response_type:
        what = await response.read()
        return tarfile.open(mode="r", fileobj=BytesIO(what))
    if "json" == response_type:
        data = await response.json(encoding=encoding)
    elif "text" == response_type:
        data = await response.text(encoding=encoding)
    else:
        data = await response.read()
    return data
848543
def is_json(mimetype):
    
    if not mimetype:
        return False
    if ";" in mimetype:  # Allow Content-Type header to be passed
        mimetype = get_mimetype(mimetype)
    if mimetype == "application/json":
        return True
    if mimetype.startswith("application/") and mimetype.endswith("+json"):
        return True
    return False
423126
def finalize_response(self, request, response, *args, **kwargs):
        
        # Make the error obvious if a proper response is not returned
        assert isinstance(response, HttpResponseBase), (
            'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
            'to be returned from the view, but received a `%s`'
            % type(response)
        )

        if isinstance(response, Response):
            if not getattr(request, 'accepted_renderer', None):
                neg = self.perform_content_negotiation(request, force=True)
                request.accepted_renderer, request.accepted_media_type = neg

            response.accepted_renderer = request.accepted_renderer
            response.accepted_media_type = request.accepted_media_type
            response.renderer_context = self.get_renderer_context()

        for key, value in self.headers.items():
            response[key] = value

        return response
877965
public static boolean checkResponseTypes(final String type, final OAuth20ResponseTypes... expectedTypes) {
        LOGGER.debug("Response type: [{}]", type);
        val checked = Stream.of(expectedTypes).anyMatch(t -> OAuth20Utils.isResponseType(type, t));
        if (!checked) {
            LOGGER.error("Unsupported response type: [{}]", type);
        }
        return checked;
    }
768880
def confirmMapIdentity(self, subject, vendorSpecific=None):
        
        response = self.confirmMapIdentityResponse(subject, vendorSpecific)
        return self._read_boolean_response(response)
202244
def render(self, data, accepted_media_type=None, renderer_context=None):
        

        wrapper = None
        success = False

        for wrapper_name in self.wrappers:
            wrapper_method = getattr(self, wrapper_name)
            try:
                wrapper = wrapper_method(data, renderer_context)
            except WrapperNotApplicable:
                pass
            else:
                success = True
                break

        if not success:
            raise WrapperNotApplicable(
                'No acceptable wrappers found for response.',
                data=data, renderer_context=renderer_context)

        renderer_context["indent"] = 4

        return super(JsonApiMixin, self).render(
            data=wrapper,
            accepted_media_type=accepted_media_type,
            renderer_context=renderer_context)
1078354
def guess_media_type(filepath):
    """"""
    o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])
    o = o.strip()
    return o
172967
function type (response) {
  return value => {
    if (!(value instanceof Error)) {
      response.setHeader(
        'Content-Type',
        lookup(typeof value === 'object' ? 'json' : 'text')
      )
    }
    return value instanceof Array ? JSON.stringify(value) : value
  }
}
506447
def content_type(self, response):
        
        if not re_html.match(response.headers.get('Content-Type').decode('utf-8')):
            self.log.warn(
                "Dropped: %s's content is not of type "
                "text/html but %s", response.url, response.headers.get('Content-Type')
            )
            return False
        else:
            return True
480977
def render_to_response(self, context, **response_kwargs):
        
        filename = os.path.basename(self.object.file.name)

        # Try to guess the content type of the given file
        content_type, _ = mimetypes.guess_type(self.object.file.name)
        if not content_type:
            content_type = 'text/plain'

        response = HttpResponse(self.object.file, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename={}'.format(filename)

        return response
518938
@Path("confirm")
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
    @SuppressWarnings("checkstyle:illegalcatch")
    public Response confirm()
    {
        Response ret = null;
        try {
            final Context context = Context.getThreadContext();
            final ContextReply reply = new ContextReply()
                            .setUserName(context.getPerson().getName())
                            .setUserLastName(context.getPerson().getLastName())
                            .setUserFirstName(context.getPerson().getFirstName())
                            .setCompanyName(context.getCompany().getName())
                            .setLocale(context.getLocale().toString());

            ret = Response.ok().type(MediaType.APPLICATION_JSON).entity(getJSONReply(reply)).build();
        } catch (final Exception e) {
            RestContext.LOG.error("Error processing data.", e);
            final ErrorReply reply = new ErrorReply()
                            .setError(e.getClass().getName())
                            .setMessage(e.getMessage())
                            .setStacktrace(ExceptionUtils.getStackTrace(e));
            ret = Response.serverError().type(MediaType.APPLICATION_JSON).entity(getJSONReply(reply)).build();
        }
        return ret;
    }
263855
def parse_media_type(media_type):
    '''
    '''
    media_type, sep, parameter = str(media_type).partition(';')
    media_type, sep, subtype = media_type.partition('/')
    return tuple(x.strip() or None for x in (media_type, subtype, parameter))
244581
def _get_media_category(is_direct_message, file_type):
        
        if is_direct_message:
            prefix = 'dm'
        else:
            prefix = 'tweet'

        if file_type in IMAGE_MIMETYPES:
            if file_type == 'image/gif':
                return prefix + '_gif'
            else:
                return prefix + '_image'
        elif file_type == 'video/mp4':
            return prefix + '_video'
1218196
def _get_acceptable_response_type():
    """"""
    if ('Accept' not in request.headers or request.headers['Accept'] in
            ALL_CONTENT_TYPES):
        return JSON
    acceptable_content_types = set(
        request.headers['ACCEPT'].strip().split(','))
    if acceptable_content_types & HTML_CONTENT_TYPES:
        return HTML
    elif acceptable_content_types & JSON_CONTENT_TYPES:
        return JSON
    else:
        # HTTP 406 Not Acceptable
        raise InvalidAPIUsage(406)