Build a ContentDisposition from a requests (PyPI) response.
10340
def parse_requests_response(response, **kwargs):
    

    return parse_headers(
        response.headers.get('content-disposition'), response.url, **kwargs)
1172917
def from_request(cls, request):
        """"""
        request_headers = HeaderDict()
        other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH']

        for header, value in iteritems(request.META):
            is_header = header.startswith('HTTP_') or header in other_headers
            normalized_header = cls._normalize_django_header_name(header)

            if is_header and value:
                request_headers[normalized_header] = value

        return request_headers
644894
def http_response(self, request):
        '''
        '''
        content_types = request.content_types
        if not content_types or self._content_type in content_types:
            response = request.response
            response.content_type = self._content_type
            response.encoding = self.charset
            response.content = self.to_bytes()
            return response
        else:
            raise HttpException(status=415, msg=request.content_types)
194040
def get_content(self):
        """"""
        url = self.build_url()
        try:
            self.content_page = requests.get(url)
            if not(self.content_page.status_code == requests.codes.ok):
                self.content_page.raise_for_status()
        except requests.exceptions.RequestException as ex:
            logging.info('A requests exception has ocurred: ' + str(ex))
            logging.error(traceback.format_exc())
            sys.exit(0)
980876
def make_response(status, headers, payload, environ):
    
    headers_dict = {}
    content_type = None
    for h in headers:
        if h[0].lower() == 'content-type':
            content_type = h[1]
        else:
            headers_dict[h[0]] = h[1]
    return HTTPResponse(body_bytes=payload, content_type=content_type,
                        status=int(status.split()[0]), headers=headers_dict)
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)
680171
def _iter_content_generator(response, decode_unicode):
    """"""
    for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode):
        if decode_unicode:
            # Replace CRLF newlines with LF, Python will handle
            # platform specific newlines if written to file.
            chunk = chunk.replace('\r\n', '\n')
            # Chunk could be ['...\r', '\n...'], stril trailing \r
            chunk = chunk.rstrip('\r')
        yield chunk
964202
def format_response(status, body_object, headers={})
      if status == 204
        body = ''
      else
        body = case response_media_type
        when 'application/json'
          JSON.pretty_generate(body_object)
        when 'application/x-www-form-urlencoded'
          URI.encode_www_form(body_object)
        when 'application/xml'
          body_object.to_s
        when 'text/plain'
          body_object
        else
          # :nocov:
          raise NotImplementedError, "unsupported response media type #{response_media_type}"
          # :nocov:
        end
      end
      [status, headers.merge({'Content-Type' => response_media_type}), [body]]
    end
1188430
def get_content_json(request):
    """"""
    result = _get_content_json()

    resp = request.response
    resp.status = "200 OK"
    resp.content_type = 'application/json'
    resp.body = json.dumps(result)
    return result, resp
1240854
def json(content, request=None, response=None, ensure_ascii=False, **kwargs):
    """"""
    if hasattr(content, 'read'):
        return content

    if isinstance(content, tuple) and getattr(content, '_fields', None):
        content = {field: getattr(content, field) for field in content._fields}
    return json_converter.dumps(content, default=_json_converter, ensure_ascii=ensure_ascii, **kwargs).encode('utf8')
84590
def get_json_response(self, content, **kwargs):
        """"""

        # Don't care to return a django form or view in the response here.
        # Remove those from the context.
        if isinstance(content, dict):
            response_content = {k: deepcopy(v) for k, v in content.items()
                                if k not in ('form', 'view') or k in ('form', 'view')
                                and not isinstance(v, (Form, View))}
        else:
            response_content = content

        return HttpResponse(content=json.dumps(response_content),
                            content_type='application/json; charset=utf-8',
                            **kwargs)
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
504615
def process_response(self, request, response, spider):
        """"""
        return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
558243
def raw_content(self, output=None, str_output=None):
        """"""
        return self._search_page(output, str_output, self.response.data, lambda regex, content: regex.search(content.decode()))
554601
def _load_response(response):
    '''
    
    '''

    try:
        data = salt.utils.json.loads(response.text)
    except ValueError:
        data = response.text

    ret = {'code': response.status_code, 'content': data}

    return ret
983260
def get_response_content_type(self):
        """"""
        if self._best_response_match is None:
            settings = get_settings(self.application, force_instance=True)
            acceptable = headers.parse_accept(
                self.request.headers.get(
                    'Accept',
                    settings.default_content_type
                    if settings.default_content_type else '*/*'))
            try:
                selected, _ = algorithms.select_content_type(
                    acceptable, settings.available_content_types)
                self._best_response_match = '/'.join(
                    [selected.content_type, selected.content_subtype])
                if selected.content_suffix is not None:
                    self._best_response_match = '+'.join(
                        [self._best_response_match, selected.content_suffix])
            except errors.NoMatch:
                self._best_response_match = settings.default_content_type

        return self._best_response_match
1019260
def get_content_html(request):
    """"""
    result = _get_content_json()

    media_type = result['mediaType']
    if media_type == COLLECTION_MIMETYPE:
        content = tree_to_html(result['tree'])
    else:
        content = result['content']

    resp = request.response
    resp.body = content
    resp.status = "200 OK"
    resp.content_type = 'application/xhtml+xml'
    return result, resp