Takes a Sijax response object and returns a
    valid Flask response object.
176036
def _make_response(sijax_response):
    """"""
    from types import GeneratorType

    if isinstance(sijax_response, GeneratorType):
        # Streaming response using a generator (non-JSON response).
        # Upon returning a response, Flask would automatically destroy
        # the request data and uploaded files - done by `flask.ctx.RequestContext.auto_pop()`
        # We can't allow that, since the user-provided callback we're executing
        # from within the generator may want to access request data/files.
        # That's why we'll tell Flask to preserve the context and we'll clean up ourselves.

        request.environ['flask._preserve_context'] = True

        # Clean-up code taken from `flask.testing.TestingClient`
        def clean_up_context():
            top = _request_ctx_stack.top
            if top is not None and top.preserved:
                top.pop()

        # As per the WSGI specification, `close()` would be called on iterator responses.
        # Let's wrap the iterator in another one, which will forward that `close()` call to our clean-up callback.
        response = Response(ClosingIterator(sijax_response, clean_up_context), direct_passthrough=True)
    else:
        # Non-streaming response - a single JSON string
        response = Response(sijax_response)

    return response
451135
def _get_artifact_response(artifact):
    
    response = flask.Response(
        artifact.data,
        mimetype=artifact.content_type)
    response.cache_control.public = True
    response.cache_control.max_age = 8640000
    response.set_etag(artifact.id)
    return response
1373438
def create_response(request, body=None, status=None, headers=None):
    # type: (BaseHttpRequest, Any, HTTPStatus, dict) -> HttpResponse
    
    if body is None:
        return HttpResponse(None, status or HTTPStatus.NO_CONTENT, headers)
    else:
        body = request.response_codec.dumps(body)
        response = HttpResponse(body, status or HTTPStatus.OK, headers)
        response.set_content_type(request.response_codec.CONTENT_TYPE)
        return response
452817
def get_response(self):
        
        res = ARBlockRes()
        for field in ["ARType", "ARUUID", "SessionKey"]:
            res.setfieldval(field, self.getfieldval(field))
        return res
752833
def _http_response(self, url, method, data=None, content_type=None,
                       schema=None, **kwargs):
        

        if schema is None:
            schema = self.schema_2

        header = {
            'content-type': content_type or 'application/json',
            'Accept': schema,
        }

        # Token specific part. We add the token in the header if necessary
        auth = self.auth
        token_required = auth.token_required
        token = auth.token
        desired_scope = auth.desired_scope
        scope = auth.scope

        if token_required:
            if not token or desired_scope != scope:
                logger.debug("Getting new token for scope: %s", desired_scope)
                auth.get_new_token()

            header['Authorization'] = 'Bearer %s' % self.auth.token

        if data and not content_type:
            data = json.dumps(data)

        path = url.format(**kwargs)
        logger.debug("%s %s", method.__name__.upper(), path)
        response = method(self.host + path,
                          data=data, headers=header, **self.method_kwargs)
        logger.debug("%s %s", response.status_code, response.reason)
        response.raise_for_status()

        return response
801494
def jsonify(self, status_code=None, message=None, headers=None):
        
        if status_code is None:
            status_code = self.status_code
        if message is None:
            message = self.message
        if headers is None:
            headers = self.headers
        response = flask.jsonify({
            'status_code': status_code,
            'error': repr(self),
            'message': message,
        })
        if status_code is not None:
            response.status_code = status_code
        if headers is not None:
            response.headers = headers
        return response
1020605
def _response_good(self, respond):
        
        if respond.status_code != requests.codes.ok:
            log.warning('Got a {} code response to {}: {}'.format(
                respond.status_code,
                respond.url,
                respond.text))
            if respond.status_code in self.errorsNotRetry:
              raise ApiError(usr_msg='Got a {} code response to {}: {}'.format(
                respond.status_code,
                respond.url,
                respond.text))
            else:
              return self._parse_response(respond)
        try:
            if (str(respond.headers['content-type']).startswith("text/html;")):
                self.result = respond.text
                return True
            else:
                self.result = respond.json()
        except (json.JSONDecodeError, ValueError):
            usr_msg = 'device server returned unexpected http response'
            dev_msg = usr_msg + ': ' + respond.text
            raise ApiError(usr_msg=usr_msg, dev_msg=dev_msg)
        if not isinstance(self.result, (list, dict)):
            msg = ('JSON not a list or dict: url: {0},'
                   'status: {1}, reason: {2}, text: {3}')
            raise ApiError(
                usr_msg=msg.format(respond.url,
                                   respond.status_code,
                                   respond.reason, respond.text))
        if ('error' not in self.result or
                ('status' not in self.result['error'] or
                 self.result['error']['status'] != 400)):
            return True
        else:
            log.warning("Got a 400 code JSON response to %s", respond.url)
            return False
700586
def _validate_response(response):
        
        try:
            response.raise_for_status()
        except requests.RequestException:
            raise RequestException(
                code=response.status_code,
                url=response.url,
                description=response.text)
        else:
            return response
748699
def from_httplib(r, **response_kw):
        

        return HTTPResponse(body=r,
                            headers=dict(r.getheaders()),
                            status=r.status,
                            version=r.version,
                            reason=r.reason,
                            strict=r.strict,
                            original_response=r,
                            **response_kw)
647241
def make_response(self,
                      data: Any = None,
                      **kwargs: Any) -> Any:
        
        """
        if not self._valid_request:
            logger.error('Request not validated, cannot make response')
            raise self.make_error('Request not validated before, cannot make '
                                  'response')

        if data is None and self.response_factory is None:
            logger.error('Response data omit, but no response factory is used')
            raise self.make_error('Response data could be omitted only when '
                                  'response factory is used')

        response_schema = getattr(self.module, 'response', None)
        if response_schema is not None:
            self._validate(data, response_schema)

        if self.response_factory is not None:
            return self.response_factory(
                *([data] if data is not None else []),
                **kwargs)
        return data
1106077
def _handle_response(self, response):
        
        if not str(response.status_code).startswith('2'):
            raise BinanceAPIException(response)
        try:
            return response.json()
        except ValueError:
            raise BinanceRequestException('Invalid Response: %s' % response.text)
767963
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
        

        encoder = JSONEncoder(
            check_circular=self.app.validate_output,
            allow_nan=False,
            sort_keys=True,
            indent=2 if self.app.pretty_output else None,
            separators=(',', ': ') if self.app.pretty_output else (',', ':')
        )
        content = encoder.encode(response)
        if jsonp:
            content_list = [jsonp.encode(encoding), b'(', content.encode(encoding), b');']
        else:
            content_list = [content.encode(encoding)]
        return self.response(status, content_type, content_list, headers=headers)
1253509
def _response(status, body=nil, headers={})
      body = [body].compact
      headers = headers.merge("Content-Type" => "application/json")
      Rack::Response.new(body, status, headers).finish
    end
83144
def post_parse_response(self, response, **kwargs):
        

        if "scope" not in response:
            try:
                _key = kwargs['state']
            except KeyError:
                pass
            else:
                if _key:
                    item = self.get_item(oauth2.AuthorizationRequest,
                                         'auth_request', _key)
                    try:
                        response["scope"] = item["scope"]
                    except KeyError:
                        pass
        return response
14692
def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
        
        errors = [errors] if not isinstance(errors, list) else errors
        return cls(code, errors)
938236
def return_response(self, value=None):
        # type: (Any) -> Tuple[Callback, Return]
        """"""
        response = Return(id=self.id, value=value)
        return self.callback, response
962040
def _server_begin_response_callback(self, response: Response):
        ''''''
        self._item_session.response = response

        if self._cookie_jar:
            self._cookie_jar.extract_cookies(response, self._item_session.request)

        action = self._result_rule.handle_pre_response(self._item_session)
        self._file_writer_session.process_response(response)

        return action == Actions.NORMAL