Constructs a new WebPage object for the response,
        using the `BeautifulSoup` module to parse the HTML.

        Parameters
        ----------

        response : requests.Response object
432414
def new_from_response(cls, response):
        
        return cls(response.url, html=response.text, headers=response.headers)
1071668
def wrap_httplib_response(response_func):
    

    def call(self, *args, **kwargs):
        _tracer = execution_context.get_opencensus_tracer()
        current_span_id = execution_context.get_opencensus_attr(
            'httplib/current_span_id')

        span = _tracer.current_span()

        # No corresponding request span is found, request not traced.
        if not span or span.span_id != current_span_id:
            return response_func(self, *args, **kwargs)

        result = response_func(self, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status))

        _tracer.end_span()
        return result

    return call
629698
def do_response(self, response_args=None, request=None, **kwargs):
        

        links = [Link(href=h, rel=OIC_ISSUER) for h in kwargs['hrefs']]

        _response = JRD(subject=kwargs['subject'], links=links)

        info = {
            'response': _response.to_json(),
            'http_headers': [('Content-type', 'application/json')]
        }

        return info
1243447
def parse(self, response):
        
        if not self.helper.parse_crawler.content_type(response):
            return

        yield self.helper.parse_crawler.pass_to_pipeline_if_article(
            response, self.allowed_domains[0], self.original_url)
372858
def make_response(body, mimetype='text/html'):
    
    from bottle import response
    response.content_type = mimetype
    return body or u''
580042
function parseResponse({ browser, history, document, response }) {
  const window      = document.defaultView;
  window._request   = response.request;
  window._response  = response;
  history.updateLocation(window, response._url);

  const done = window._eventQueue.waitForCompletion();
  response
    ._consume()
    .then(function(body) {

      const contentType = response.headers.get('Content-Type') || '';
      const html        = getHTMLFromResponseBody(body, contentType);
      response.body     = html;
      document.write(html || '<html></html>');
      document.close();

      browser.emit('loaded', document);
      if (response.status >= 400)
        throw new Error(`Server returned status code ${response.status} from ${response.url}`);
      if (!document.documentElement)
        throw new Error(`Could not parse document at ${response.url}`);

    })
    .then(function() {

      // Handle meta refresh.  Automatically reloads new location and counts
      // as a redirect.
      //
      // If you need to check the page before refresh takes place, use this:
      //   browser.wait({
      //     function: function() {
      //       return browser.query('meta[http-equiv="refresh"]');
      //     }
      //   });
      const refresh = getMetaRefresh(document);

      if (refresh) {
        const { refreshTimeout } = refresh;
        const { refreshURL }     = refresh;

        window._eventQueue.setTimeout(function() {
          // Allow completion function to run
          window._eventQueue.enqueue(function() {
            window._eventQueue.enqueue(function() {
              // Count a meta-refresh in the redirects count.
              history.replace(refreshURL);
              // This results in a new window getting loaded
              const newWindow = history.current.window;
              newWindow.addEventListener('load', function() {
                ++newWindow._request._redirectCount;
              });
            });
          });
        }, refreshTimeout * 1000);
      }

    })
    .catch(function(error) {
      browser.emit('error', error);
    })
    .then(done);
}
1235675
def httpResponse_bodyParse(self, **kwargs):
        

        str_response    = ''
        for k,v in kwargs.items():
            if k == 'response': str_response    = v
        try:
            str_body        = str_response.split('\r\n\r\n')[1]
            d_body          = yaml.load(str_body)
            str_body        = json.dumps(d_body)
        except:
            str_body        = str_response
        return str_body
713861
def _new_render(response):
    
    orig_render = response.__class__.render

    # No arguments, is used as bound method.
    def _inner_render():
        try:
            return orig_render(response)
        except HttpRedirectRequest as e:
            return HttpResponseRedirect(e.url, status=e.status)

    return _inner_render
1286042
def _handle_response(self):
        
        content = self.cache['restbase']['info']['content-type']
        if content.startswith('text/html'):
            html = self.cache['restbase']['response']
            if isinstance(html, bytes):
                html = html.decode('utf-8')
            self.data['html'] = html
            return

        response = self._load_response('restbase')

        http_status = self.cache['restbase']['info']['status']
        if http_status == 404:
            raise LookupError(self.cache['restbase']['query'])

        if self.params.get('endpoint') == '/page/':
            msg = "RESTBase /page/ entry points: %s" % response.get('items')
            utils.stderr(msg)
            del self.cache['restbase']
            return

        return response
43823
def _parse_response(header_data, ignore_bad_cookies=False,
                    ignore_bad_attributes=True):
    
    cookie_dicts = []
    for line in Definitions.EOL.split(header_data.strip()):
        if not line:
            break
        cookie_dict = parse_one_response(
            line, ignore_bad_cookies=ignore_bad_cookies,
            ignore_bad_attributes=ignore_bad_attributes)
        if not cookie_dict:
            continue
        cookie_dicts.append(cookie_dict)
    if not cookie_dicts:
        if not ignore_bad_cookies:
            raise InvalidCookieError(data=header_data)
        _report_invalid_cookie(header_data)
    return cookie_dicts
839223
def parse_response(self, resp):
        
        p, u = self.getparser()

        if hasattr(resp,'text'):
            # modern requests will do this for us
            text = resp.text # this is unicode(py2)/str(py3)
        else:

            encoding = requests.utils.get_encoding_from_headers(resp.headers)
            if encoding is None:
                encoding='utf-8' # FIXME: what to do here?

            if sys.version_info[0]==2:
                text = unicode(resp.content, encoding, errors='replace')
            else:
                assert sys.version_info[0]==3
                text = str(resp.content, encoding, errors='replace')
        p.feed(text)
        p.close()
        return u.close()
10340
def parse_requests_response(response, **kwargs):
    

    return parse_headers(
        response.headers.get('content-disposition'), response.url, **kwargs)
735934
def _scrape_response(self, headers, response):
        
        # identify the responding server
        server_type = None
        server_string = headers.get('server', '')

        if server_string and 'jetty' in server_string.lower():
            server_type = 'jetty'

        if server_string and 'coyote' in server_string.lower():
            server_type = 'tomcat'

        reason = None
        full_html = ''
        dom_tree = None

        # In Python3, response can be made of bytes
        if IS_PY3 and hasattr(response, 'decode'):
            response = response.decode()
        if response.startswith('<?xml'):
            # Try a strict XML parse
            try:
                soup = ElementTree.fromstring(response)

                reason_node = soup.find('lst[@name="error"]/str[@name="msg"]')
                tb_node = soup.find('lst[@name="error"]/str[@name="trace"]')
                if reason_node is not None:
                    full_html = reason = reason_node.text.strip()
                if tb_node is not None:
                    full_html = tb_node.text.strip()
                    if reason is None:
                        reason = full_html

                # Since we had a precise match, we'll return the results now:
                if reason and full_html:
                    return reason, full_html
            except ElementTree.ParseError:
                # XML parsing error, so we'll let the more liberal code handle it.
                pass

        if server_type == 'tomcat':
            # Tomcat doesn't produce a valid XML response or consistent HTML:
            m = re.search(r'<(h1)[^>]*>\s*(.+?)\s*</\1>', response, re.IGNORECASE)
            if m:
                reason = m.group(2)
            else:
                full_html = "%s" % response
        else:
            # Let's assume others do produce a valid XML response
            try:
                dom_tree = ElementTree.fromstring(response)
                reason_node = None

                # html page might be different for every server
                if server_type == 'jetty':
                    reason_node = dom_tree.find('body/pre')
                else:
                    reason_node = dom_tree.find('head/title')

                if reason_node is not None:
                    reason = reason_node.text

                if reason is None:
                    full_html = ElementTree.tostring(dom_tree)
            except SyntaxError as err:
                LOG.warning('Unable to extract error message from invalid XML: %s', err,
                            extra={'data': {'response': response}})
                full_html = "%s" % response

        full_html = force_unicode(full_html)
        full_html = full_html.replace('\n', '')
        full_html = full_html.replace('\r', '')
        full_html = full_html.replace('<br/>', '')
        full_html = full_html.replace('<br />', '')
        full_html = full_html.strip()
        return reason, full_html
258081
def _build_response(self):
        
        responses = []
        self.event_urls = []

        for index, event in enumerate(self.events):
            self.py3.threshold_get_color(index + 1, "event")
            self.py3.threshold_get_color(index + 1, "time")

            event_dict = {}

            event_dict["summary"] = event.get("summary")
            event_dict["location"] = event.get("location")
            event_dict["description"] = event.get("description")
            self.event_urls.append(event["htmlLink"])

            if event["start"].get("date") is not None:
                start_dt = self._gstr_to_date(event["start"].get("date"))
                end_dt = self._gstr_to_date(event["end"].get("date"))
            else:
                start_dt = self._gstr_to_datetime(event["start"].get("dateTime"))
                end_dt = self._gstr_to_datetime(event["end"].get("dateTime"))

            if end_dt < datetime.datetime.now(tzlocal()):
                continue

            event_dict["start_time"] = self._datetime_to_str(start_dt, self.format_time)
            event_dict["end_time"] = self._datetime_to_str(end_dt, self.format_time)

            event_dict["start_date"] = self._datetime_to_str(start_dt, self.format_date)
            event_dict["end_date"] = self._datetime_to_str(end_dt, self.format_date)

            time_delta = self._delta_time(start_dt)
            if time_delta["days"] < 0:
                time_delta = self._delta_time(end_dt)
                is_current = True
            else:
                is_current = False

            event_dict["format_timer"] = self._format_timedelta(
                index, time_delta, is_current
            )

            if self.warn_threshold > 0:
                self._check_warn_threshold(time_delta, event_dict)

            event_formatted = self.py3.safe_format(
                self.format_event,
                {
                    "is_toggled": self.button_states[index],
                    "summary": event_dict["summary"],
                    "location": event_dict["location"],
                    "description": event_dict["description"],
                    "start_time": event_dict["start_time"],
                    "end_time": event_dict["end_time"],
                    "start_date": event_dict["start_date"],
                    "end_date": event_dict["end_date"],
                    "format_timer": event_dict["format_timer"],
                },
            )

            self.py3.composite_update(event_formatted, {"index": index})
            responses.append(event_formatted)

            self.no_update = False

        format_separator = self.py3.safe_format(self.format_separator)
        self.py3.composite_update(format_separator, {"index": "sep"})
        responses = self.py3.composite_join(format_separator, responses)

        return {"events": responses}
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
10815
def _serialize(self):
        

        # Do something appropriate if the response object is unbound
        if self._defcode is None:
            raise exceptions.UnboundResponse()

        # Build the response
        resp = self.response_class(request=self.req, status=self.code,
                                   headerlist=self._headers.items())

        # Do we have a body?
        if self.result:
            resp.content_type = self.content_type
            resp.body = self.serializer(self.result)

        # Return the response
        return resp
1144170
def _parse_response_for_dict(response):
    ''' '''

    if response is None:
        return None
    http_headers = ['server', 'date', 'location', 'host',
                    'via', 'proxy-connection', 'connection']
    return_dict = _HeaderDict()
    if response.headers:
        for name, value in response.headers:
            if not name.lower() in http_headers:
                return_dict[name] = value

    return return_dict