Write response body to file
493819
public void writeToFile(File file) {
        try {
            try (OutputStream os = new FileOutputStream(file)) {
                InputStreams.transferTo(body(), os);
            }
        } catch (IOException e) {
            throw new RequestsException(e);
        } finally {
            close();
        }
    }
225217
function writeTile(file, url, request, callback) {
  // Result of request
  let res = null;

  // FileWriteStream
  let fileStream = fs.createWriteStream(file);

  // Register finish callback of FileWriteStream
  fileStream.on('finish', () => {
    callback(null, res);
  });

  // Register error callback of FileWriteStream
  fileStream.on('error', (err) => {
    callback(err, res);
  });

  // Request object
  let req = request.get(url);

  // Register error callback of request
  req.on('error', (err) => {
    callback(err, res);
  });

  // Register response callback of request
  req.on('response', (response) => {
    res = response;
  });

  // Start download
  req.pipe(fileStream);
}
368054
private void writeResponse(final HttpServletResponse response, final String data) throws IOException {
    final byte[] outputBody = data.getBytes(StandardCharsets.UTF_8);
    response.getOutputStream().write(outputBody);
  }
915654
def write(self, data):
        """"""
        cnpj, data = data

        path = os.path.join(self.output, '%s.json' % cnpj)
        with open(path, 'w') as f:
            json.dump(data, f, encoding='utf-8')
1309621
def write_payload(payload=None, objectInput=None):
    

    temp = tempfile.mkstemp()[1]
    log.debug("Write payload in temp file {!r}".format(temp))

    with open(temp, 'wb') as f:
        if payload:
            payload = base64.b64decode(payload)
        elif objectInput:
            if six.PY3:
                payload = objectInput.buffer.read()
            elif six.PY2:
                payload = objectInput.read()

        f.write(payload)

    return temp
1247933
@Override
	protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response)
			throws IOException, ResourceNotFoundException {

		String resourceName = requestedPath;
		if (!jawrConfig.getGeneratorRegistry().isGeneratedBinaryResource(resourceName)
				&& !resourceName.startsWith(URL_SEPARATOR)) {
			resourceName = URL_SEPARATOR + resourceName;
		}

		try (InputStream is = rsReaderHandler.getResourceAsStream(resourceName);
				OutputStream os = response.getOutputStream()) {
			IOUtils.copy(is, os);
		} catch (EOFException eofex) {
			LOGGER.debug("Browser cut off response", eofex);
		} catch (IOException e) {
			if (ClientAbortExceptionResolver.isClientAbortException(e)) {
				LOGGER.debug("Browser cut off response", e);
			} else {
				throw e;
			}
		}
	}
1171508
def file_response(data: Union[bytes, str],  # HttpResponse encodes str if req'd
                  content_type: str,
                  filename: str) -> HttpResponse:
    
    response = HttpResponse(data, content_type=content_type)
    add_download_filename(response, filename)
    return response
715164
def save_headers(cls, filename: str, response: HTTPResponse):
        '''
        '''
        new_filename = filename + '-new'

        with open('wb') as new_file:
            new_file.write(response.header())

            with wpull.util.reset_file_offset(response.body):
                response.body.seek(0)
                shutil.copyfileobj(response.body, new_file)

        os.remove(filename)
        os.rename(new_filename, filename)
1133543
def build_response(body, status = 200, headers = {})
      @template = { body: body, status: status, headers: headers }
    end
698456
function writeDataToFile (file, data, token) {
  // insertionPoint was set in hasInsertionPoint(), so we can assume it is safe to write to file
  var selectors = [
    'head > meta:last-of-type',
    'head > link:first-of-type',
    'head'
  ]
  var selectorIndex = 0

  switch (insertionPoint) {
    case 'meta':
      selectorIndex = 0
      break
    case 'link':
      selectorIndex = 1
      break
    case 'head':
      selectorIndex = 2
      break
    case 'token':
      let html = String(file.contents).replace(token, data)
      return new Buffer(html)
    default:
      return ''
  }

  var soup = new Soup(String(file.contents))

  // Inject Resource Hints
  soup.setInnerHTML(selectors[selectorIndex], function (oldHTML) {
    if (insertionPoint === 'link') {
      return data + oldHTML
    }
    return oldHTML + data
  })

  return soup.toString()
}
768280
private void dumpResponse(final HttpServletResponseLoggingWrapper response, final int id) {
        final StringWriter stringWriter = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(stringWriter);
        printWriter.print("-- ID: ");
        printWriter.println(id);
        printWriter.println(response.getStatusCode());
        if (LOG_HEADERS.isDebugEnabled()) {
            final Map<String, List<String>> headers = response.headers;
            for (Map.Entry<String, List<String>> header : headers.entrySet()) {
                printWriter.print(header.getKey());
                printWriter.print(": ");
                Iterator<String> values = header.getValue().iterator();
                while (values.hasNext()) {
                    printWriter.print(values.next());
                    printWriter.println();
                    if (values.hasNext()) {
                        printWriter.print(' ');
                    }
                }
            }
        }
        printWriter.println("-- Begin response body");

        final String body = response.getContentAsInputString();
        if (body == null || body.length() == 0) {
            printWriter.println("-- NO BODY WRITTEN IN RESPONSE");
        } else {
            printWriter.println(body);
        }
        printWriter.println();
        printWriter.println("-- End response body");
        printWriter.flush();
        LOG_RESPONSE.debug(stringWriter.toString());
    }
479868
def write(self):
        """"""
        if (self.data):
            dataPath = self.client.local_dir / (urllib.parse.quote_plus(self.uri)+'.json')
            with dataPath.open(mode='w') as dump_file:
                json.dump(self.data, dump_file)
                dump_file.close()
            logger.info('Wrote ' + self.uri + ' to file')
            return True
        else:
            logger.warning('No data to write for ' + self.uri)
            return False
1129687
def write(url, content, **args):
    """"""
    relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot'))
    try:
        smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL,
                                          keyfile=args.pop('keyfile', None),
                                          certfile=args.pop('certfile', None))
    except AttributeError:
        def smtplib_SMTPS():
            raise ValueError(relay.geturl())
    filename = args.pop('filename', '')
    content_type, encoding = mimetypes.guess_type(filename)
    content_type = args.pop('content_type', content_type)
    encoding = args.pop('content_encoding', encoding)
    maintype, subtype = content_type.split('/')
    content = content_types.get(content_types).format(content, **args)
    content = content_encodings.get(encoding).encode(content)
    message = {
        'application': application.MIMEApplication,
        'text': text.MIMEText}[maintype](content, subtype)
    if filename:
        message.set_param('filename', ('UTF-8', '', filename.decode('UTF-8')))
    if encoding:
        message['Content-Encoding'] = encoding
    message['To'] = urllib.unquote(url.path)
    for name, value in urlparse.parse_qsl(url.query):
        message[name.replace('_', '-')] = value
    if message['From'] is None:
        username = os.environ.get('USERNAME')
        username = os.environ.get('LOGNAME', username)
        username = os.environ.get('USER', username)
        message['From'] = '{}@{}'.format(username, socket.getfqdn())

    # ``mailto`` scheme allow for a body param. We don't.
    del message['body']

    # Send the email.
    client = {'smtp': smtplib.SMTP,
              'lmtp': smtplib.LMTP,
              'smtps': smtplib_SMTPS}[relay.scheme]()
    client.connect(''.join([relay.hostname, relay.path]), relay.port)
    if relay.username and relay.password:
        client.login(relay.username, relay.password)
    client.sendmail(message['From'], [message['To']], message.as_string())
    client.quit()
842800
function mockResponseBody (req, res, next) {
  if (res.swagger) {
    if (res.swagger.isEmpty) {
      // There is no response schema, so send an empty response
      util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path);
      res.send();
    }
    else {
      // Serialize the response body according to the response schema
      let schema = new JsonSchema(res.swagger.schema);
      let serialized = schema.serialize(res.swagger.wrap(res.body));

      switch (res.swagger.schema.type) {
        case "object":
        case "array":
        case undefined:
          sendObject(req, res, next, serialized);
          break;

        case "file":
          sendFile(req, res, next, serialized);
          break;

        default:
          sendText(req, res, next, serialized);
      }
    }
  }
  else {
    next();
  }
}
250862
def write_data(self, data, response_required=None, timeout=5.0, raw=False):
        """"""
        if self._transport is None:
            return

        if self._paused:
            return

        if self._waiting_for_response:
            LOG.debug("queueing write %s", data)
            self._queued_writes.append((data, response_required, timeout))
            return

        if response_required:
            self._waiting_for_response = response_required
            if timeout > 0:
                self._timeout_task = self.loop.call_later(
                    timeout, self._response_required_timeout)

        if not raw:
            cksum = 256 - reduce(lambda x, y: x+y, map(ord, data)) % 256
            data = data + '{:02X}'.format(cksum)
            if int(data[0:2], 16) != len(data)-2:
                LOG.debug("message length wrong: %s", data)

        LOG.debug("write_data '%s'", data)
        self._transport.write((data + '\r\n').encode())
1272831
def dump_to_response(request, app_label=None, exclude=None,
                     filename_prefix=None):
    
    app_label = app_label or []
    exclude = exclude
    try:
        filename = '%s.%s' % (datetime.now().isoformat(),
                              settings.SMUGGLER_FORMAT)
        if filename_prefix:
            filename = '%s_%s' % (filename_prefix, filename)
        if not isinstance(app_label, list):
            app_label = [app_label]
        response = serialize_to_response(app_label, exclude)
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response
    except CommandError as e:
        messages.error(
            request,
            _('An exception occurred while dumping data: %s') % force_text(e))
    return HttpResponseRedirect(request.build_absolute_uri().split('dump')[0])
351487
def log_response(_, _request, response, *_args, **kwargs):
    # type: (Any, ClientRequest, ClientResponse, str, Any) -> Optional[ClientResponse]
    
    if not _LOGGER.isEnabledFor(logging.DEBUG):
        return None

    try:
        _LOGGER.debug("Response status: %r", response.status_code)
        _LOGGER.debug("Response headers:")
        for res_header, value in response.headers.items():
            _LOGGER.debug("    %r: %r", res_header, value)

        # We don't want to log binary data if the response is a file.
        _LOGGER.debug("Response content:")
        pattern = re.compile(r'attachment; ?filename=["\w.]+', re.IGNORECASE)
        header = response.headers.get('content-disposition')

        if header and pattern.match(header):
            filename = header.partition('=')[2]
            _LOGGER.debug("File attachments: %s", filename)
        elif response.headers.get("content-type", "").endswith("octet-stream"):
            _LOGGER.debug("Body contains binary data.")
        elif response.headers.get("content-type", "").startswith("image"):
            _LOGGER.debug("Body contains image data.")
        else:
            if kwargs.get('stream', False):
                _LOGGER.debug("Body is streamable")
            else:
                _LOGGER.debug(response.text())
        return response
    except Exception as err:  # pylint: disable=broad-except
        _LOGGER.debug("Failed to log response: %s", repr(err))
        return response