Convert string into Response and content.

        Args:
          payload: Header and body string to be deserialized.

        Returns:
          A Response object
174229
def _DeserializeResponse(self, payload):
        
        # Strip off the status line.
        status_line, payload = payload.split('\n', 1)
        _, status, _ = status_line.split(' ', 2)

        # Parse the rest of the response.
        parser = email_parser.Parser()
        msg = parser.parsestr(payload)

        # Get the headers.
        info = dict(msg)
        info['status'] = status

        # Create Response from the parsed headers.
        content = msg.get_payload()

        return http_wrapper.Response(info, content, self.__batch_url)
457749
def parse(self, charset=None, headers=None):
        

        if headers:
            self.headers = headers
        else:
            # Parse headers only from last response
            # There could be multiple responses in `self.head`
            # in case of 301/302 redirect
            # Separate responses
            if self.head:
                responses = self.head.rsplit(b'\nHTTP/', 1)
                # Cut off the 'HTTP/*' line from the last response
                _, response = responses[-1].split(b'\n', 1)
                response = response.decode('utf-8', 'ignore')
            else:
                response = u''
            if six.PY2:
                # email_from_string does not work with unicode input
                response = response.encode('utf-8')
            self.headers = email.message_from_string(response)

        if charset is None:
            if isinstance(self.body, six.text_type):
                self.charset = 'utf-8'
            else:
                self.detect_charset()
        else:
            self.charset = charset.lower()

        self._unicode_body = None
27198
def _maybe_deserialize_body(self):
        
        if not self.content_type:
            return self._message_body
        ct = headers.parse_content_type(self.content_type)
        key = '{}/{}'.format(ct.content_type, ct.content_subtype)
        if key not in self._SERIALIZATION_MAP:
            if key not in self._IGNORE_TYPES:
                self.logger.debug('Unsupported content-type: %s',
                                  self.content_type)
            return self._message_body
        elif not self._SERIALIZATION_MAP[key].get('enabled', True):
            self.logger.debug('%s is not enabled in the serialization map',
                              key)
            return self._message_body
        value = self._message_body
        if not self._SERIALIZATION_MAP[key].get('binary'):
            value = self._maybe_decode(
                self._message_body, ct.parameters.get('charset', 'utf-8'))
        return self._maybe_invoke_serialization(value, 'load', key)
725990
def _convert(self, payload):
        
        if not isinstance(payload, six.string_types):
            payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True)
        return str(payload)
532247
private byte[] readBody(Map<String, List<String>> headers, WebSocketInputStream input)
    {
        // Get the value of "Content-Length" header.
        int length = getContentLength(headers);

        if (length <= 0)
        {
            // Response body is not available.
            return null;
        }

        try
        {
            // Allocate a byte array of the content length.
            byte[] body = new byte[length];

            //  into the byte array.
            input.readBytes(body, length);

            // Return the content of the response body.
            return body;
        }
        catch (Throwable t)
        {
            // Response body is not available.
            return null;
        }
    }
286396
def from_response(cls, response_data):
        
        identity = lambda x: x
        return Mail(**_transform_dict(response_data, {
            'guid': ('mail_id', identity),
            'subject': ('mail_subject', identity),
            'sender': ('mail_from', identity),
            'datetime': ('mail_timestamp', lambda x: datetime.utcfromtimestamp(int(x)).replace(tzinfo=utc)),
            'read': ('mail_read', int),
            'excerpt': ('mail_excerpt', identity),
            'body': ('mail_body', identity),
        }))
839223
def parse_response(self, resp):
        
        p, u = self.getparser()

        if hasattr(resp,'text'):
            # modern requests will do this for us
            text = resp.text # this is unicode(py2)/str(py3)
        else:

            encoding = requests.utils.get_encoding_from_headers(resp.headers)
            if encoding is None:
                encoding='utf-8' # FIXME: what to do here?

            if sys.version_info[0]==2:
                text = unicode(resp.content, encoding, errors='replace')
            else:
                assert sys.version_info[0]==3
                text = str(resp.content, encoding, errors='replace')
        p.feed(text)
        p.close()
        return u.close()
1174237
def _parse_response(proto, response):
        
        try:
            content = proto()
            content.ParseFromString(response.content)
            return content
        except (DecodeError, AttributeError):
            LOGGER.error('Validator response was not parsable: %s', response)
            raise errors.ValidatorResponseInvalid()
510815
def make_response(body, mimetype='text/html'):
    
    from werkzeug.wrappers import Response
    if isinstance(body, Response):
        body.mimetype = mimetype
        return body
    return Response(body, mimetype=mimetype)
650389
def get_request_body_chunk(self, content: bytes, closed: bool,
                               more_content: bool) -> Dict[str, Any]:
        '''
        
        '''
        return {
            'content': content,
            'closed': closed,
            'more_content': more_content
        }
872217
def _get_pretty_body(headers, body):
    

    if HEADER_CONTENT_TYPE in headers:
        if HEADER_REPRESENTATION_XML == headers[HEADER_CONTENT_TYPE]:
            xml_parsed = parseString(body)
            pretty_xml_as_string = xml_parsed.toprettyxml()
            return pretty_xml_as_string
        else:
            if HEADER_REPRESENTATION_JSON in headers[HEADER_CONTENT_TYPE]:
                parsed = json.loads(body)
                return json.dumps(parsed, sort_keys=True, indent=4)
            else:
                return body
    else:
        return body
335913
def parse(self, response):
        
        self.headers = response.headers

        if 'xml' in self.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        lines = response.text.split('\r\n')
        if len(lines) < 3:
            lines = response.text.split('\n')

        for line in lines:
            line = line.strip()

            name, value = self.read_line(line)
            if name:
                if name in self.valid_transactions or re.match(pattern='/^X\-/', string=name):
                    self.capabilities[name] = value
                else:
                    self.details[name] = value
676854
def string_to_response(content_type):
    
    def outer_wrapper(req_function):
        @wraps(req_function)
        def newreq(request, *args, **kwargs):
            try:
                outp = req_function(request, *args, **kwargs)
                if issubclass(outp.__class__, HttpResponse):
                    response = outp
                else:
                    response = HttpResponse()
                    response.write(outp)
                    response['Content-Length'] = str(len(response.content))

                response['Content-Type'] = content_type

            except HttpBadRequestException as bad_request:
                response = HttpResponseBadRequest(bad_request.message)

            return response
        return newreq
    return outer_wrapper
1286025
def eventdata(payload):
    

    headerinfo, data = payload.split('\n', 1)
    headers = get_headers(headerinfo)
    return headers, data
10340
def parse_requests_response(response, **kwargs):
    

    return parse_headers(
        response.headers.get('content-disposition'), response.url, **kwargs)
549063
def insert(self, payload):
        
        response = self.session.post(self._get_table_url(), data=json.dumps(payload))
        return self._get_content(response)
507971
def body(self):
        """"""

        if self._decoded_body == None:
            # Try to decode the JSON body. But raise an error if the
            # content-type is unexpected, or the JSON is invalid.

            raw_content_type = self.request.headers.get("content-type") or ""
            content_type = raw_content_type.split(";")[0].strip().lower()

            if content_type == "application/json":
                try:
                    self._decoded_body = escape.json_decode(self.request.body)
                except:
                    raise oz.json_api.ApiError("Bad JSON body")
            else:
                raise oz.json_api.ApiError("JSON body expected")

        return self._decoded_body