Build a framework specific HTPP response, containing ``body`` and
    marked as the type ``mimetype``.
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)
367626
def _BuildStreamingResponse(self, binary_stream, method_name=None):
    """"""
    precondition.AssertType(method_name, Text)

    # We get a first chunk of the output stream. This way the likelihood
    # of catching an exception that may happen during response generation
    # is much higher.
    content = binary_stream.GenerateContent()
    try:
      peek = content.next()
      stream = itertools.chain([peek], content)
    except StopIteration:
      stream = []

    response = werkzeug_wrappers.Response(
        response=stream,
        content_type="binary/octet-stream",
        direct_passthrough=True)
    response.headers["Content-Disposition"] = ((
        "attachment; filename=%s" % binary_stream.filename).encode("utf-8"))
    if method_name:
      response.headers["X-API-Method"] = method_name.encode("utf-8")

    if binary_stream.content_length:
      response.content_length = binary_stream.content_length

    return response
869438
def build_request_body(header_params, form_params, body)
      # http form
      if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
          header_params['Content-Type'] == 'multipart/form-data'
        data = {}
        form_params.each do |key, value|
          case value
          when ::File, ::Array, nil
            # let typhoeus handle File, Array and nil parameters
            data[key] = value
          else
            data[key] = value.to_s
          end
        end
      elsif body
        data = body.is_a?(String) ? body : body.to_json
      else
        data = nil
      end
      data
    end
340634
def _get_response_mime_type(self):
        
        view_name = self.request.view_name
        if view_name != '':
            mime_type = get_registered_mime_type_for_name(view_name)
        else:
            mime_type = None
            acc = None
            for acc in self.request.accept:
                if acc == '*/*':
                    # The client does not care; use the default.
                    mime_type = self.__get_default_response_mime_type()
                    break
                try:
                    mime_type = \
                            get_registered_mime_type_for_string(acc.lower())
                except KeyError:
                    pass
                else:
                    break
            if mime_type is None:
                if not acc is None:
                    # The client specified a MIME type we can not handle; this
                    # is a 406 exception. We supply allowed MIME content
                    # types in the body of the response.
                    headers = \
                        [('Location', self.request.path_url),
                         ('Content-Type', TextPlainMime.mime_type_string),
                         ]
                    mime_strings = get_registered_mime_strings()
                    exc = HTTPNotAcceptable('Requested MIME content type(s) '
                                            'not acceptable.',
                                            body=','.join(mime_strings),
                                            headers=headers)
                    raise exc
                mime_type = self.__get_default_response_mime_type()
        return mime_type
862137
def request(self, method, uri, **kw):
        
        expect = kw.pop("expect", [])
        mime_body = kw.pop("mime_body", None)

        headers = kw.pop("headers", {})
        data = kw.pop("data", None)

        if mime_body:
            mimevalues = self.mimeobjects.get(mime_body.__class__)

            if not mimevalues:
                raise ClientException(
                    ("Cannot handle object of type "
                     "{0!r}").format(mime_body.__class__))

            mapping = mimevalues[0]

            document_type, mimetype, validator = mapping

            data = document_type.render(validator, mime_body)
            headers["Content-Type"] = mimetype

        if uri[0] != '/':
            uri = '/' + uri

        url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)

        response = self.session.request(
            method, url,
            headers=headers,
            data=data,
            **kw)

        content_type = response.headers.get("Content-Type")

        if content_type is None or not response.content:
            return response, None

        mimetype, opts = werkzeug.http.parse_options_header(content_type)

        if mimetype not in self.mimetypes:
            raise ClientException(
                "Cannot handle response type: {0}".format(mimetype))

        document_type, document_class, validator = self.mimetypes.get(mimetype)

        if expect and document_class not in expect:
            raise ClientException(
                "Unexpected response type: {0}".format(mimetype))

        try:
            obj = document_type.parse(validator,
                                      document_class,
                                      response.content)
        except MimeValidationError as e:
            raise ClientException(
                "Response format invalid: {0}".format(str(e)))
        except:
            log.error(
                "Failed to parse content of type: {0}".format(mimetype),
                exc_info=sys.exc_info())
            raise ClientException(
                "Failed to parse content of type: {0}".format(mimetype))

        return response, obj
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)
14692
def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
        
        errors = [errors] if not isinstance(errors, list) else errors
        return cls(code, errors)
1306397
def encode_contents(self):
        

        if self.variable_size:
            resp_length = 1
        else:
            resp_length = self.fixed_response_size << 1

        header = struct.pack("<HBB", self.rpc_id, self.address, resp_length)
        return bytearray(header) + self.payload
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
753509
def _update_response_body(self, resource):
        
        rpr = self._get_response_representer(resource)
        # Set content type and body of the response.
        self.request.response.content_type = \
                                rpr.content_type.mime_type_string
        rpr_body = rpr.to_bytes(resource)
        self.request.response.body = rpr_body
10791
function createResponse(request, response, body){
  return {
    statusCode: response.statusCode,
    statusText: response.statusMessage,
    headers: response.headers,
    originalUrl: request.url,
    effectiveUrl: request.url,
    redirected: false,
    requestMethod: request.method,
    requestHeaders: request.headers,
    body: body,
    retries: 0,
    throttled: false
  };
}
983159
def page_response(self, title='', body=''):
        
        f = StringIO()
        f.write('<!DOCTYPE html>\n')
        f.write('<html>\n')
        f.write('<head><title>{}</title><head>\n'.format(title))
        f.write('<body>\n<h2>{}</h2>\n'.format(title))
        f.write('<div class="content">{}</div>\n'.format(body))
        f.write('</body>\n</html>\n')
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        encoding = sys.getfilesystemencoding()
        self.send_header("Content-type", "text/html; charset=%s" % encoding)
        self.send_header("Content-Length", str(length))
        self.end_headers()
        self.copyfile(f, self.wfile)
        f.close()
1001993
def __body_format(self, body):
        

        ctype, pdict = parse_header(self.content_type)
        if ctype == 'application/json':
            self.form = json.loads(body.decode())

        elif ctype == 'application/x-www-form-urlencoded':
            for key, value in parse_qs(body).items():
                    self.form[key.decode()] = [one_value.decode() for one_value in value]

        elif ctype == "multipart/form-data":
            safe_env = {
                'QUERY_STRING': '',
                'REQUEST_METHOD': self.method.upper(),
                'CONTENT_TYPE': self.content_type,
                'CONTENT_LENGTH': self.headers.get('Content-Length', '-1')
            }
            fields = FieldStorage(io.BytesIO(body), environ=safe_env, keep_blank_values=True)

            fields = fields.list or []
            for field in fields:
                if field.filename:
                    self.form[field.name] = File(field.filename, field.file)
                else:
                    self.form[field.name] = field.value
1022456
def send_response(self, body, set_content_type=True):
        
        settings = get_settings(self.application, force_instance=True)
        handler = settings[self.get_response_content_type()]
        content_type, data_bytes = handler.to_bytes(body)
        if set_content_type:
            self.set_header('Content-Type', content_type)
            self.add_header('Vary', 'Accept')
        self.write(data_bytes)
382414
def _prep_binary_mimetype(self):

		'''
		
		'''

		# neither present
		if not self.mimetype and 'Content-Type' not in self.resource.headers.keys():
			raise Exception('to create/update NonRDFSource, mimetype or Content-Type header is required')

		# mimetype, no Content-Type
		elif self.mimetype and 'Content-Type' not in self.resource.headers.keys():
			logger.debug('setting Content-Type header with provided mimetype: %s'
				% self.mimetype)
			self.resource.headers['Content-Type'] = self.mimetype
919933
def html(body, status=200, headers=None):
    '''
    
    '''
    return HTTPResponse(body, status=status, headers=headers,
                        content_type='text/html; charset=utf-8')
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