Write response body to file
968844
public void writeToFile(Path path) {
        try {
            try (OutputStream os = Files.newOutputStream(path)) {
                InputStreams.transferTo(body(), os);
            }
        } catch (IOException e) {
            throw new RequestsException(e);
        } finally {
            close();
        }
    }
606282
def __stringify_body(self, request_or_response):
        '''  '''
        headers = self.__track_info['{}_headers'.format(request_or_response)]
        body = self.__track_info.get('{}_body'.format(request_or_response))
    
        if isinstance(body, CaseInsensitiveDict):
            body = json.dumps(dict(body), ensure_ascii=False)
    
        elif isinstance(body, (dict, list)):
            body = json.dumps(body, indent=2, ensure_ascii=False)
    
        elif isinstance(body, bytes):
            resp_content_type = headers.get("Content-Type", "")
            try:
                if "image" in resp_content_type:
                    self.__track_info["response_data_type"] = "image"
                    body = "data:{};base64,{}".format(
                        resp_content_type,
                        b64encode(body).decode('utf-8')
                    )
                else:
                    body = escape(body.decode("utf-8"))
            except UnicodeDecodeError:
                pass
    
        elif not isinstance(body, (basestring, numeric_types, Iterable)):
            # class instance, e.g. MultipartEncoder()
            body = repr(body)
    
        self.__track_info['{}_body'.format(request_or_response)] = body
1245857
private void writeBufferToFile() throws IOException {
        if (_bufferOffset > 0) {
            List<ByteBuffer> payload = new ArrayList<ByteBuffer>(1);
            payload.add(ByteBuffer.wrap(_buffer, 0, _bufferOffset));
            NfsWriteResponse response = _nfsFile.write(_currentOffset, payload, _syncType);
            int bytesWritten = response.getCount();
            _currentOffset += bytesWritten;
            _bufferOffset -= bytesWritten;
            if (0 != _bufferOffset) { // Everything was not written.
                // _bufferOffset should be the number of unwritten bytes.
                // Copy the unwritten bytes to the beginning of the buffer.
                System.arraycopy(_buffer, bytesWritten, _buffer, 0, _bufferOffset);
            }
        }
    }
187328
def _gzip(self, response):
        """"""
        bytesio = six.BytesIO()
        with gzip.GzipFile(fileobj=bytesio, mode='w') as gz:
            gz.write(response)
        return bytesio.getvalue()
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')
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();
  }
}
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
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])
249827
def raw(body, status=200, headers=None,
        content_type='application/octet-stream'):
    '''
    
    '''
    return HTTPResponse(body_bytes=body, status=status, headers=headers,
                        content_type=content_type)
29044
protected void writeResponse(HttpServletResponse response, ApiResponse sresponse) {
        response.setStatus(sresponse.getCode());
        for (Entry<String, String> entry : sresponse.getHeaders()) {
            response.addHeader(entry.getKey(), entry.getValue());
        }
    }
344791
def to_file(f)
      result = client.query(last_statement, :stream => true, :cache_rows => false, :as => :array)
      escaped_fields = result.fields.map { |k| k.to_xs }

      f.write %{<?xml version="1.0" encoding="utf-8" ?>}
      f.write %{<resultset statement="#{config.execute.to_xs}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">}
      result.each do |ary|
        next if ary.nil?
        f.write %{<row>}
        ary.each_with_index do |v, i|
          f.write %{<field name="#{escaped_fields[i]}"#{' xsi:nil="true"' if v.nil?}>#{v.to_s.to_xs}</field>}
        end
        f.write %{</row>}
      end
      f.write %{</resultset>}
      nil
    end
517661
def write_raw(self, resp: Union[bytes, requests.Response], filename: str) -> None:
        """"""
        self.log(filename, end=' ', flush=True)
        with open(filename, 'wb') as file:
            if isinstance(resp, requests.Response):
                shutil.copyfileobj(resp.raw, file)
            else:
                file.write(resp)
521738
public static void responseFile(HttpServletResponse response, String local, boolean isDownloaded) throws IOException {
        if (Checker.isExists(local)) {
            File file = new File(local);
            try (FileInputStream in = new FileInputStream(file); ServletOutputStream os = response.getOutputStream()) {
                byte[] b;
                while (in.available() > 0) {
                    b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];
                    in.read(b, 0, b.length);
                    os.write(b, 0, b.length);
                }
                os.flush();
            }
            if (isDownloaded) {
                String fn = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                response.setHeader("Content-Disposition", "attachment;filename=" + fn);
            }
        } else {
            response.setStatus(404);
        }
    }
191748
def save(filename, path, params={})
      payload = get! path, nil, params
      File.write filename, payload.response.body
    end
567297
def write_object_to_file(self, obj, path='.', filename=None):
        """"""
        output = self.json_dumps(obj) + '\n'
        if filename is None:
            filename = self.safe_filename(obj['_type'], obj['_id'])
        filename = os.path.join(path, filename)
        self.pr_inf("Writing to file: " + filename)
        with open(filename, 'w') as f:
            f.write(output)
        # self.pr_dbg("Contents: " + output)
        return filename
543037
def prepare_body(self, data, files):
        """"""

        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        body = None
        content_type = None
        length = None

        is_stream = all([
            hasattr(data, '__iter__'),
            not isinstance(data, (basestring, list, tuple, dict))
        ])

        try:
            length = super_len(data)
        except (TypeError, AttributeError, UnsupportedOperation):
            length = None

        if is_stream:
            body = data

            if files:
                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')

            if length is not None:
                self.headers['Content-Length'] = builtin_str(length)
            else:
                self.headers['Transfer-Encoding'] = 'chunked'
        else:
            # Multi-part file uploads.
            if files:
                (body, content_type) = self._encode_files(files, data)
            else:
                if data:
                    body = self._encode_params(data)
                    if isinstance(data, basestring) or hasattr(data, 'read'):
                        content_type = None
                    else:
                        content_type = 'application/x-www-form-urlencoded'

            self.prepare_content_length(body)

            # Add content-type if it wasn't explicitly provided.
            if (content_type) and (not 'content-type' in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body
521790
protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response)
			throws IOException, ResourceNotFoundException {

		// Send gzipped resource if user agent supports it.
		int idx = requestedPath.indexOf(BundleRenderer.GZIP_PATH_PREFIX);
		if (idx != -1) {

			requestedPath = JawrConstant.URL_SEPARATOR
					+ requestedPath.substring(idx + BundleRenderer.GZIP_PATH_PREFIX.length(), requestedPath.length());
			if (isValidRequestedPath(requestedPath)) {
				response.setHeader(CONTENT_ENCODING, GZIP);
				bundlesHandler.streamBundleTo(requestedPath, response.getOutputStream());
			} else {
				throw new ResourceNotFoundException(requestedPath);
			}

		} else {

			// In debug mode, we take in account the image generated from a
			// StreamGenerator like classpath Image generator
			// The following code will rewrite the URL path for the generated
			// images,
			// because in debug mode, we are retrieving the CSS resources
			// directly from the webapp
			// and if the CSS contains generated images, we should rewrite the
			// URL.
			BinaryResourcesHandler imgRsHandler = (BinaryResourcesHandler) servletContext
					.getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
			if (imgRsHandler != null && this.jawrConfig.isDebugModeOn() && resourceType.equals(JawrConstant.CSS_TYPE)) {

				handleGeneratedCssInDebugMode(requestedPath, request, response, imgRsHandler);
			} else {

				if (isValidRequestedPath(requestedPath)) {
					Writer out = response.getWriter();
					bundlesHandler.writeBundleTo(requestedPath, out);
				} else {
					throw new ResourceNotFoundException(requestedPath);
				}
			}
		}
	}