This function is called during :meth:`send_response`.

        We override it to get a little more information logged in a somewhat
        better format.  We do not use the size  method argument.
500956
def log_request(self, code='-', size='-'):
        #  pylint: disable=unused-argument
        
        self.log('%s: HTTP status %s',
                 (self._get_log_prefix(), code),
                 logging.INFO)
186184
def send_response_message(self, request_id, meta, body):
        
        self.response_messages.append((request_id, meta, body))
1039782
def _makeResponse(self, urllib2_response):
        '''
        
        '''
        resp = HTTPResponse()
        resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024)
        resp.final_url = urllib2_response.geturl()
        resp.headers = self._lowerCaseKeys(
            dict(list(urllib2_response.info().items())))

        if hasattr(urllib2_response, 'code'):
            resp.status = urllib2_response.code
        else:
            resp.status = 200

        _, extra_dict = self._parseHeaderValue(
            resp.headers.get("content-type", ""))
        # Try to decode the response body to a string, if there's a
        # charset known; fall back to ISO-8859-1 otherwise, since that's
        # what's suggested in HTTP/1.1
        charset = extra_dict.get('charset', 'latin1')
        try:
            resp.body = resp.body.decode(charset)
        except Exception:
            pass

        return resp
309247
def _send_size(self):
        "  "
        rows, cols = _get_size(sys.stdout.fileno())
        self._send_packet({
            'cmd': 'size',
            'data': [rows, cols]
        })
913662
def send(self, **kwargs):
        
        return_full_object = kwargs.get('return_full_object', False)
        _verbose = kwargs.get('_verbose', False)
        traversal = kwargs.get('traversal', None)
        timeout = kwargs.get('_timeout', 5)
        self.output['url'] = self.render_url()
        with VerboseContextManager(verbose=_verbose):
            try:
                resp = Response(self.action.format(), request(timeout=timeout, **self.output), traversal)
            except HTTPError as err:
                raise ResponseException(self.action.format(), err)
            except socket.timeout:
                raise RequestTimeout(functools.partial(self.send, **kwargs))
            except URLError as err:
                if isinstance(err.reason, socket.timeout):
                    raise RequestTimeout(functools.partial(self.send, **kwargs))
                else:
                    raise

        if return_full_object:
            return resp
        else:
            return resp.read()
1006513
function sendResponse (req, res, next, dataStore) {
  return function (err, resources) {
    if (!err) {
      util.debug("%s successfully updated", res.swagger.location);

      if (resources.length > 0) {
        // Determine the max "modifiedOn" date of the resources
        res.swagger.lastModified = _.max(resources, "modifiedOn").modifiedOn;
      }
      else {
        // There is no data, so use the current date/time as the "last-modified" header
        res.swagger.lastModified = new Date();
      }

      // Extract the "data" of each Resource
      resources = _.map(resources, "data");
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (!res.swagger.isCollection) {
      // Response body is a single value, so only return the first item that was edited
      res.body = _.first(resources);
      next();
    }
    else {
      // Response body is the entire collection (new, edited, and old)
      dataStore.getCollection(req.path, (err, collection) => {
        res.body = _.map(collection, "data");
        next(err);
      });
    }
  };
}
1000727
async def send_message(  # type: ignore
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:
        
        headers = dict(self.DEFAULT_HEADERS)
        headers.update(kwargs.pop("headers", {}))

        response = await self.client.fetch(
            self.endpoint, method="POST", body=request, headers=headers, **kwargs
        )

        return Response(response.body.decode(), raw=response)
362294
def receive_message(sock, request_id, max_message_size=MAX_MESSAGE_SIZE):
    """"""
    # Ignore the response's request id.
    length, _, response_to, op_code = _UNPACK_HEADER(
        _receive_data_on_socket(sock, 16))
    # No request_id for exhaust cursor "getMore".
    if request_id is not None:
        if request_id != response_to:
            raise ProtocolError("Got response id %r but expected "
                                "%r" % (response_to, request_id))
    if length <= 16:
        raise ProtocolError("Message length (%r) not longer than standard "
                            "message header size (16)" % (length,))
    if length > max_message_size:
        raise ProtocolError("Message length (%r) is larger than server max "
                            "message size (%r)" % (length, max_message_size))
    if op_code == 2012:
        op_code, _, compressor_id = _UNPACK_COMPRESSION_HEADER(
            _receive_data_on_socket(sock, 9))
        data = decompress(
            _receive_data_on_socket(sock, length - 25), compressor_id)
    else:
        data = _receive_data_on_socket(sock, length - 16)

    try:
        unpack_reply = _UNPACK_REPLY[op_code]
    except KeyError:
        raise ProtocolError("Got opcode %r but expected "
                            "%r" % (op_code, _UNPACK_REPLY.keys()))
    return unpack_reply(data)
655791
def _get_response(self):
        
        try:
            self._open_connection()
            if self.connection is None:
                # The connection wasn't opened, which means we're deferring a reconnection attempt.
                # Raise a socket.error, so we'll return the same server_disconnected message as we
                # do below.
                raise socket.error('Delaying reconnection attempt')

            header = self._read_socket(self.HEADER_SIZE)
            (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque,
             cas) = struct.unpack(self.HEADER_STRUCT, header)

            assert magic == self.MAGIC['response']

            extra_content = None
            if bodylen:
                extra_content = self._read_socket(bodylen)

            return (magic, opcode, keylen, extlen, datatype, status, bodylen,
                    opaque, cas, extra_content)
        except socket.error as e:
            self._connection_error(e)

            # (magic, opcode, keylen, extlen, datatype, status, bodylen, opaque, cas, extra_content)
            message = str(e)
            return (self.MAGIC['response'], -1, 0, 0, 0, self.STATUS['server_disconnected'], 0, 0, 0, message)
406152
function sendResponse (req, res, next, dataStore) {
  return function (err, resource) {
    if (!err) {
      util.debug("%s successfully created/edited/deleted", resource.toString());
      res.swagger.lastModified = resource.modifiedOn;
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (res.swagger.isCollection) {
      // Response body is the entire collection
      dataStore.getCollection(resource.collection, (err, collection) => {
        res.body = _.map(collection, "data");
        next(err);
      });
    }
    else {
      // Response body is the resource that was created/update/deleted
      res.body = resource.data;
      next();
    }
  };
}
829019
def _format_response(self, request, response):
        

        res = datamapper.format(request, response, self)
        # data is now formatted, let's check if the status_code is set
        if res.status_code is 0:
            res.status_code = 200
        # apply headers
        self._add_resposne_headers(res, response)
        return res
949213
def respond(self):
        """"""
        mrbs = self.server.max_request_body_size
        if self.chunked_read:
            self.rfile = ChunkedRFile(self.conn.rfile, mrbs)
        else:
            cl = int(self.inheaders.get("Content-Length", 0))
            if mrbs and mrbs < cl:
                if not self.sent_headers:
                    self.simple_response("413 Request Entity Too Large",
                        "The entity sent with the request exceeds the maximum "
                        "allowed bytes.")
                return
            self.rfile = KnownLengthRFile(self.conn.rfile, cl)
        
        self.server.gateway(self).respond()
        
        if (self.ready and not self.sent_headers):
            self.sent_headers = True
            self.send_headers()
        if self.chunked_write:
            self.conn.wfile.sendall("0\r\n\r\n")
1356314
def process_response(self, request, response):
        
        try:
            log_dict = create_log_dict(request, response)

            # add the request time to the log_dict; if no start time is
            # available, use -1 as NA value
            request_time = (
                time.time() - self.start_time if hasattr(self, 'start_time')
                and self.start_time else -1)
            log_dict.update({'request_time': request_time})

            is_request_time_too_high = (
                request_time > float(settings.LOGUTILS_REQUEST_TIME_THRESHOLD))
            use_sql_info = settings.DEBUG or is_request_time_too_high

            log_msg = create_log_message(log_dict, use_sql_info, fmt=False)

            if is_request_time_too_high:
                logger.warning(log_msg, log_dict, extra=log_dict)
            else:
                logger.info(log_msg, log_dict, extra=log_dict)
        except Exception as e:
            logger.exception(e)

        return response
137510
def _handle_response(self, response, data):
        
        # Content-Type headers can include additional parameters(RFC 1521), so
        # we split on ; to match against only the type/subtype
        if data and response.get('content-type', '').split(';')[0] in (
            'application/json', 
            'application/x-javascript',
            'text/javascript',
            'text/x-javascript',
            'text/x-json'
        ):
            return json.loads(data)
        else:
            return data
357958
def do_POST(self):
        

        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).
            max_chunk_size = 10*1024*1024
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                chunk = self.rfile.read(chunk_size)
                if not chunk:
                    break
                L.append(chunk)
                size_remaining -= len(L[-1])
            data = b''.join(L)

            data = self.decode_request_content(data)
            if data is None:
                return #response has been sent

            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None), self.path
                )
        except Exception as e: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
                trace = traceback.format_exc()
                trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII')
                self.send_header("X-traceback", trace)

            self.send_header("Content-length", "0")
            self.end_headers()
        else:
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            if self.encode_threshold is not None:
                if len(response) > self.encode_threshold:
                    q = self.accept_encodings().get("gzip", 0)
                    if q:
                        try:
                            response = gzip_encode(response)
                            self.send_header("Content-Encoding", "gzip")
                        except NotImplementedError:
                            pass
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
284770
public void sendResponse(HttpResponse resp, boolean close) throws IOException {
		StringBuilder header = new StringBuilder();
		header.append("HTTP/1.1").append(' ').append(resp.getStatus().getCode()).append(' ').append(resp.getStatus());
		header.append('\r').append('\n');
		// Set the content type header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_TYPE)) {
			resp.addHeader(HttpHeader.CONTENT_TYPE, "text/html; charset=utf-8");
		}
		// Set the content length header if it's not already set
		if (!resp.getHeaders().containsKey(HttpHeader.CONTENT_LENGTH)) {
			resp.addHeader(HttpHeader.CONTENT_LENGTH, resp.getResponseLength());
		}
		// Copy in the headers
		for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
			String headerName = HttpUtil.capitalizeHeader(entry.getKey());
			for (Object o : entry.getValue()) {
				header.append(headerName);
				header.append(':').append(' ');
				header.append(o);
				header.append('\r').append('\n');
			}
		}
		header.append('\r').append('\n');
		// Write the header
		output.write(header.toString().getBytes("UTF-8"));

		// Ignore the body for headers and no content
		if (request != null && request.getMethod() == HttpMethod.HEAD || resp.getStatus() == HttpStatus.NO_CONTENT) {
			if (resp.getResponse() instanceof InputStream) {
				((InputStream) resp.getResponse()).close();
			}
		} else {
			// Responses can be InputStreams or Strings
			if (resp.getResponse() instanceof InputStream) {
				// InputStreams will block the session thread (No big deal) and send
				// data without loading it into memory
				InputStream res = resp.getResponse();
				try {
					long remaining = resp.getResponseLength();
					// Write the body
					byte[] buffer = new byte[1024];
					while (remaining > 0) {
						int read = res.read(buffer, 0, remaining > buffer.length ? buffer.length : (int) remaining);
						if (read == -1) {
							break;
						}

						output.write(buffer, 0, read);

						remaining -= read;
					}
				} finally {
					res.close();
				}
			} else if (resp.getResponse() instanceof String) {
				String responseString = resp.getResponse();
				output.write(responseString.getBytes("UTF-8"));
			} else if (resp.getResponse() instanceof byte[]) {
				output.write((byte[]) resp.getResponse());
			}
		}
		// Close it if required.
		if (close) {
			socket.close();
		}
	}

	/**
	 * Send an HttpStatus
	 *
	 * @param status The status to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status) throws IOException {
		sendResponse(new HttpResponse(status, status.toString()));
	}

	/**
	 * Send an HttpStatus with the specified error message
	 *
	 * @param status The status to send
	 * @param message The error message to send
	 * @throws IOException If an error occurred while sending
	 */
	public void sendError(HttpStatus status, String message) throws IOException {
		sendResponse(new HttpResponse(status, status.toString() + ':' + message));
	}

	/**
	 * Get the remote address from this session
	 *
	 * @return The remote address
	 */
	public InetSocketAddress getRemoteAddress() {
		return (InetSocketAddress) socket.getRemoteSocketAddress();
	}
}
1328906
def send_message(
        self, request: str, response_expected: bool, **kwargs: Any
    ) -> Response:
        
        response = self.session.post(self.endpoint, data=request.encode(), **kwargs)
        return Response(response.text, raw=response)