Returns a new Response with no format data.
 Used to dispatch the individual format methods.
9820
def method_missing(name, &block)
      @formats.push([name, block || proc {}]) unless @formats.any? {|n,b| n == name}
    end
713967
def _wrap_response(request, data=None, metadata=None, status=200):
        
        envelope = metadata or {}

        if data is not None:
            envelope['data'] = data

        return web.Response(
            status=status,
            content_type='application/json',
            text=json.dumps(
                envelope,
                indent=2,
                separators=(',', ': '),
                sort_keys=True))
38451
def _handler_response(self, response, data=None):
        
        if response.status_code == 200:
            data = response.json()
            if isinstance(data, dict) and data.get("error_code"):

                raise WeiboAPIError(data.get("request"), data.get("error_code"), data.get("error"))
            else:
                return data
        else:
            raise WeiboRequestError(
                "Weibo API request error: status code: {code} url:{url} ->"
                " method:{method}: data={data}".format(
                    code=response.status_code,
                    url=response.url,
                    method=response.request.method,
                    data=data
                )
            )
330883
def process_response(response)
        raise ArgumentError, 'response is null' if response.nil?

        if block_given?
          yield
        end


        # return code
        if 401 == response.code
          raise UnauthorizedError, compose_error_message(response)
        elsif 500 == response.code
          raise ServerError, compose_error_message(response)
        elsif 2 != (response.code / 100)
          raise OrientdbError, "unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}"
        end

        content_type = response.headers[:content_type] if connection_library == :restclient
        content_type = response.headers['Content-Type'] if connection_library == :excon
        content_type ||= 'text/plain'

        rslt = case
          when content_type.start_with?('text/plain')
            response.body
          when content_type.start_with?('application/x-gzip')
            response.body
          when content_type.start_with?('application/json')
            ::JSON.parse(response.body)
          else
            raise OrientdbError, "unsuported content type: #{content_type}"
          end

        rslt
      end
354857
def respond(self, data, format='json'):
        
        dispatchers = {
            "dict": self.__respond_with_dict,
            "list": self.__respond_with_list
        }

        if not dispatchers.get(format, False):
            return json.dumps(data)

        return dispatchers[format](data)
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
419607
def method_missing(method_name, *args, &block)
      return @raw_data[method_name.to_s] if @raw_data.key?(method_name.to_s)
      return @raw_data.method(method_name.to_s).call(*args, &block) if @raw_data.respond_to?(method_name.to_s)
      super
    end
11441
def create_response(self, data=None):
        
        frame = deepcopy(self)
        if data is not None:
            frame.data = data
        frame.length = 2 + len(frame.data)
        return frame
432414
def new_from_response(cls, response):
        
        return cls(response.url, html=response.text, headers=response.headers)
1220845
def format_response(self, response_data):
        """"""

        _addr, length = self.response_info()
        if len(response_data) != length:
            raise HardwareError("Invalid response read length, should be the same as what response_info() returns", expected=length, actual=len(response_data))

        resp, flags, received_length, payload = struct.unpack("<HxBL4x20s", response_data)
        resp = resp & 0xFF
        if flags & (1 << 3):
            raise HardwareError("Could not grab external gate")

        if received_length > 20:
            raise HardwareError("Invalid received payload length > 20 bytes", received_length=received_length)

        payload = payload[:received_length]

        return {
            'status': resp,
            'payload': payload
        }
771409
def data(self, data=None):
        
        if data is not None:
            self.response_model.data = data
        return self.response_model.data
943493
def _build_response(data, renderer=None):
    
    if isinstance(data, Response) or isinstance(data, BaseResponse):
        return data
    if not renderer:
        raise AttributeError(" Renderer is required")
    if isinstance(data, dict) or data is None:
        data = {} if data is None else data
        for _ in __view_parsers:
            data = _(data)
        return renderer(data), 200
    elif isinstance(data, tuple):
        data, status, headers = _normalize_response_tuple(data)
        for _ in __view_parsers:
            data = _(data)
        return renderer(data or {}), status, headers
    return data
1176867
def _output_format(cls, func, override=None):
        
        @wraps(func)
        def _format_wrapper(self, *args, **kwargs):
            call_response, data_key, meta_data_key = func(
                self, *args, **kwargs)
            if 'json' in self.output_format.lower() or 'pandas' \
                    in self.output_format.lower():
                data = call_response[data_key]
                if meta_data_key is not None:
                    meta_data = call_response[meta_data_key]
                else:
                    meta_data = None
                # Allow to override the output parameter in the call
                if override is None:
                    output_format = self.output_format.lower()
                elif 'json' or 'pandas' in override.lower():
                    output_format = override.lower()
                # Choose output format
                if output_format == 'json':
                    return data, meta_data
                elif output_format == 'pandas':
                    if isinstance(data, list):
                        # If the call returns a list, then we will append them
                        # in the resulting data frame. If in the future
                        # alphavantage decides to do more with returning arrays
                        # this might become buggy. For now will do the trick.
                        data_array = []
                        for val in data:
                            data_array.append([v for _, v in val.items()])
                        data_pandas = pandas.DataFrame(data_array, columns=[
                            k for k, _ in data[0].items()])
                    else:
                        data_pandas = pandas.DataFrame.from_dict(data,
                                                                 orient='index',
                                                                 dtype=float)
                    data_pandas.index.name = 'date'
                    if 'integer' in self.indexing_type:
                        # Set Date as an actual column so a new numerical index
                        # will be created, but only when specified by the user.
                        data_pandas.reset_index(level=0, inplace=True)
                    return data_pandas, meta_data
            elif 'csv' in self.output_format.lower():
                return call_response, None
            else:
                raise ValueError('Format: {} is not supported'.format(
                    self.output_format))
        return _format_wrapper
245886
def convert_response(response)
      HttpResponse.new(response.status, response.headers, response.body)
    end
1267415
def to_instance(self, response):
        
        klass = self.schema['title']
        cls = get_model_class(klass, api=self.__api__)
        jdict = json.loads(response.content, encoding="utf-8")
        ### check if we have a response
        properties_dict = jdict[self.schema['title']]
        # @todo: find a way to handle the data
        # validation fails if the none values are not removed
        new_dict = helpers.remove_properties_containing_None(properties_dict)
        #jdict[self.schema['title']] = new_dict
        obj = cls(new_dict)
        #obj.links = jdict[self.schema['title']]['links']
        return obj
434692
def from_response(self, response):
        
        for name in self.PROPERTIES:
            attr = '_{0}'.format(name)
            transform = self.PROPERTIES[name].get('transform', None)
            value = response.get(name, None)
            if transform and transform == TRANSFORM.TIME and value:
                setattr(self, attr, dateutil.parser.parse(value))
            if isinstance(value, int) and value == 0:
                continue  # skip attribute
            else:
                setattr(self, attr, value)

        return self
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])