Generate a successful HTTP response.
971125
def _ok(self, packets=None, headers=None, b64=False):
        """"""
        if packets is not None:
            if headers is None:
                headers = []
            if b64:
                headers += [('Content-Type', 'text/plain; charset=UTF-8')]
            else:
                headers += [('Content-Type', 'application/octet-stream')]
            return {'status': '200 OK',
                    'headers': headers,
                    'response': payload.Payload(packets=packets).encode(b64)}
        else:
            return {'status': '200 OK',
                    'headers': [('Content-Type', 'text/plain')],
                    'response': b'OK'}
1012855
def build_response(content, code=200):
    """"""
    response = make_response( jsonify(content), content['code'] )
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = \
            'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    return response
1372161
def make_response(event):
    """"""
    code, message = event.status
    response = jsonify(**event.response)
    response.headers['X-Hub-Event'] = event.receiver_id
    response.headers['X-Hub-Delivery'] = event.id
    if message:
        response.headers['X-Hub-Info'] = message
    add_link_header(response, {'self': url_for(
        '.event_item', receiver_id=event.receiver_id, event_id=event.id,
        _external=True
    )})
    return response, code
833459
async def send_http_response(writer,
                             http_code: int,
                             headers: List[Tuple[str, str]],
                             content: bytes,
                             http_status: str= None
                             ) -> None:
    
    # generate response payload
    if not http_status:
        http_status = STATUS_CODES.get(http_code, 'Unknown')

    response: bytes = f'HTTP/1.1 {http_code} {http_status}\r\n'.encode()
    for k, v in headers:
        response += f'{k}: {v}\r\n'.encode()
    response += b'\r\n'
    response += content

    # send payload
    writer.write(response)
    await writer.drain()
561019
def process_response(self, request, response, resource, req_succeeded):
        """"""
        self.logger.info(self._generate_combined_log(request, response))
573029
def execute(self):
        
        url = os.path.join(self.HTTP_ENDPOINT, self.format)
        self.response = ExportResponse.load_http_response(
            self.session.post(url, data=self.json_payload)
        )
        return self.response.result
474826
def process_response(self, request, response, resource, req_succeeded):
        """"""
        sid = request.cookies.get(self.cookie_name, None)
        if sid is None or not self.store.exists(sid):
            sid = self.generate_sid()

        self.store.set(sid, request.context.get(self.context_name, {}))
        response.set_cookie(self.cookie_name, sid, expires=self.cookie_expires, max_age=self.cookie_max_age,
                            domain=self.cookie_domain, path=self.cookie_path, secure=self.cookie_secure,
                            http_only=self.cookie_http_only)
300966
function success(response, body) {
  var content = _.assign(body || {}, {success: true});
  send(response, content, StatusCode.ok);
}
504615
def process_response(self, request, response, spider):
        """"""
        return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
294773
def success(request, message, extra_tags='', fail_silently=False, async=False):
    """"""
    if ASYNC and async:
        messages.success(_get_user(request), message)
    else:
        add_message(request, constants.SUCCESS, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)
810552
def http(self, *args, **kwargs):
        """"""
        kwargs['api'] = self.api
        return http(*args, **kwargs)
1145341
def simple_response(self, status, msg=''):
        """"""
        status = str(status)
        proto_status = '%s %s\r\n' % (self.server.protocol, status)
        content_length = 'Content-Length: %s\r\n' % len(msg)
        content_type = 'Content-Type: text/plain\r\n'
        buf = [
            proto_status.encode('ISO-8859-1'),
            content_length.encode('ISO-8859-1'),
            content_type.encode('ISO-8859-1'),
        ]

        if status[:3] in ('413', '414'):
            # Request Entity Too Large / Request-URI Too Long
            self.close_connection = True
            if self.response_protocol == 'HTTP/1.1':
                # This will not be true for 414, since read_request_line
                # usually raises 414 before reading the whole line, and we
                # therefore cannot know the proper response_protocol.
                buf.append(b'Connection: close\r\n')
            else:
                # HTTP/1.0 had no 413/414 status nor Connection header.
                # Emit 400 instead and trust the message body is enough.
                status = '400 Bad Request'

        buf.append(CRLF)
        if msg:
            if isinstance(msg, six.text_type):
                msg = msg.encode('ISO-8859-1')
            buf.append(msg)

        try:
            self.conn.wfile.write(EMPTY.join(buf))
        except socket.error as ex:
            if ex.args[0] not in errors.socket_errors_to_ignore:
                raise
516560
function sendResponse(success) {
        success = success || false;
        response.status(200);
        response.contentType('application/json');
        response.send(JSON.stringify({success: success}));
      }
839210
def RenderHttpResponse(request):
  """"""

  start_time = time.time()
  response = HTTP_REQUEST_HANDLER.HandleRequest(request)
  total_time = time.time() - start_time

  method_name = response.headers.get("X-API-Method", "unknown")
  if response.status_code == 200:
    status = "SUCCESS"
  elif response.status_code == 403:
    status = "FORBIDDEN"
  elif response.status_code == 404:
    status = "NOT_FOUND"
  elif response.status_code == 501:
    status = "NOT_IMPLEMENTED"
  else:
    status = "SERVER_ERROR"

  if request.method == "HEAD":
    metric_name = "api_access_probe_latency"
  else:
    metric_name = "api_method_latency"

  stats_collector_instance.Get().RecordEvent(
      metric_name, total_time, fields=(method_name, "http", status))

  return response
929551
def _get(self, url, params=None, headers=None):
        """"""
        url = self.clean_url(url)
        response = requests.get(url, params=params, verify=self.verify,
                                timeout=self.timeout, headers=headers)
        return 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();
	}
}
1362687
def success(self, request, message, extra_tags='', fail_silently=False):
        """"""
        add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags,
            fail_silently=fail_silently)