Log a server response.

    :param _: Unused in current version (will be None)
    :param requests.Request request: The request object.
    :param requests.Response response: The response object.
351487
def log_response(_, _request, response, *_args, **kwargs):
    # type: (Any, ClientRequest, ClientResponse, str, Any) -> Optional[ClientResponse]
    
    if not _LOGGER.isEnabledFor(logging.DEBUG):
        return None

    try:
        _LOGGER.debug("Response status: %r", response.status_code)
        _LOGGER.debug("Response headers:")
        for res_header, value in response.headers.items():
            _LOGGER.debug("    %r: %r", res_header, value)

        # We don't want to log binary data if the response is a file.
        _LOGGER.debug("Response content:")
        pattern = re.compile(r'attachment; ?filename=["\w.]+', re.IGNORECASE)
        header = response.headers.get('content-disposition')

        if header and pattern.match(header):
            filename = header.partition('=')[2]
            _LOGGER.debug("File attachments: %s", filename)
        elif response.headers.get("content-type", "").endswith("octet-stream"):
            _LOGGER.debug("Body contains binary data.")
        elif response.headers.get("content-type", "").startswith("image"):
            _LOGGER.debug("Body contains image data.")
        else:
            if kwargs.get('stream', False):
                _LOGGER.debug("Body is streamable")
            else:
                _LOGGER.debug(response.text())
        return response
    except Exception as err:  # pylint: disable=broad-except
        _LOGGER.debug("Failed to log response: %s", repr(err))
        return response
1269093
def write_response(self, response):
        
        if self._response_timeout_handler:
            self._response_timeout_handler.cancel()
            self._response_timeout_handler = None
        try:
            keep_alive = self.keep_alive
            self.transport.write(
                response.output(
                    self.request.version, keep_alive, self.keep_alive_timeout
                )
            )
            self.log_response(response)
        except AttributeError:
            logger.error(
                "Invalid response object for url %s, "
                "Expected Type: HTTPResponse, Actual Type: %s",
                self.url,
                type(response),
            )
            self.write_error(ServerError("Invalid response type"))
        except RuntimeError:
            if self._debug:
                logger.error(
                    "Connection lost before response written @ %s",
                    self.request.ip,
                )
            keep_alive = False
        except Exception as e:
            self.bail_out(
                "Writing response failed, connection closed {}".format(repr(e))
            )
        finally:
            if not keep_alive:
                self.transport.close()
                self.transport = None
            else:
                self._keep_alive_timeout_handler = self.loop.call_later(
                    self.keep_alive_timeout, self.keep_alive_timeout_callback
                )
                self._last_response_time = time()
                self.cleanup()
1372227
def process_response(self, request, response):
        

        if request.is_ajax() and hasattr(request, 'horizon'):
            queued_msgs = request.horizon['async_messages']
            if type(response) == http.HttpResponseRedirect:
                # Drop our messages back into the session as per usual so they
                # don't disappear during the redirect. Not that we explicitly
                # use django's messages methods here.
                for tag, message, extra_tags in queued_msgs:
                    getattr(django_messages, tag)(request, message, extra_tags)
                # if response['location'].startswith(settings.LOGOUT_URL):
                #     redirect_response = http.HttpResponse(status=401)
                #     # This header is used for handling the logout in JS
                #     redirect_response['logout'] = True
                #     if self.logout_reason is not None:
                #         utils.add_logout_reason(
                #             request, redirect_response, self.logout_reason)
                # else:
                redirect_response = http.HttpResponse()
                # Use a set while checking if we want a cookie's attributes
                # copied
                cookie_keys = set(('max_age', 'expires', 'path', 'domain',
                                   'secure', 'httponly', 'logout_reason'))
                # Copy cookies from HttpResponseRedirect towards HttpResponse
                for cookie_name, cookie in six.iteritems(response.cookies):
                    cookie_kwargs = dict((
                        (key, value) for key, value in six.iteritems(cookie)
                        if key in cookie_keys and value
                    ))
                    redirect_response.set_cookie(
                        cookie_name, cookie.value, **cookie_kwargs)
                redirect_response['X-Horizon-Location'] = response['location']
                upload_url_key = 'X-File-Upload-URL'
                if upload_url_key in response:
                    self.copy_headers(response, redirect_response,
                                      (upload_url_key, 'X-Auth-Token'))
                return redirect_response
            if queued_msgs:
                # TODO(gabriel): When we have an async connection to the
                # client (e.g. websockets) this should be pushed to the
                # socket queue rather than being sent via a header.
                # The header method has notable drawbacks (length limits,
                # etc.) and is not meant as a long-term solution.
                response['X-Horizon-Messages'] = json.dumps(queued_msgs)
        return response
561019
def process_response(self, request, response, resource, req_succeeded):
        """"""
        self.logger.info(self._generate_combined_log(request, response))
955937
def response(request)
      response = responses.fetch(@response_counter, responses.last)
      if response.respond_to?(:call)
        response = response.call(request)
      end
      @response_counter += 1
      response.mock = @from || true
      response
    end
1169329
def dispatch_request(self, req):
        
        log.debug("Dispatching request: {}".format(str(req)))

        # make sure it's valid
        res = None
        try:
            req.validate()
        except MissingFieldError as e:
            res = APIMissingFieldErrorResponse(str(e))

        # dispatch the request
        if not res:
            try:
                res = req.dispatch()
            except Exception as e:
                msg = "Exception raised while dispatching request: {}".format(repr(e))
                log.exception(msg)
                res = APIGenericErrorResponse(msg)

        log.debug("Response: {}".format(str(res)))

        return res
360960
function (request) {
             // This function is the default logging function.
                return {
                    host: request.headers.host,
                    method: request.method,
                    timestamp: new Date(),
                    url: request.url
                };
            }
884263
def _after_request(self, response):
        
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return response

        try:
            tracer = execution_context.get_opencensus_tracer()
            tracer.add_attribute_to_current_span(
                HTTP_STATUS_CODE,
                str(response.status_code))
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
        finally:
            return response
686991
def log_request_success(self, method, full_url, path, body, status_code, response, duration):
        
        #  TODO: optionally pass in params instead of full_url and do urlencode only when needed

        # body has already been serialized to utf-8, deserialize it for logging
        # TODO: find a better way to avoid (de)encoding the body back and forth
        if body:
            try:
                body = body.decode('utf-8', 'ignore')
            except AttributeError:
                pass

        logger.info(
            '%s %s [status:%s request:%.3fs]', method, full_url,
            status_code, duration
        )
        logger.debug('> %s', body)
        logger.debug('< %s', response)

        self._log_trace(method, path, body, status_code, response, duration)
323073
def _server_response_handler(self, response: Dict[str, Any]):
        
        code = response.get("CODE")
        if code == 100:
            if self.debug:
                print("auth succeed")
            self._login_fut.set_result(response)
        if code == 101:
            if self.debug:
                print('pong')
        return True
66326
def _log_function(self, handler):
        
        if handler.get_status() < 400:
            log_method = request_log.info
        elif handler.get_status() < 500:
            log_method = request_log.warning
        else:
            log_method = request_log.error
        for i in settings['LOGGING_IGNORE_URLS']:
            if handler.request.uri.startswith(i):
                log_method = request_log.debug
                break

        request_time = 1000.0 * handler.request.request_time()
        log_method("%d %s %.2fms", handler.get_status(),
                   handler._request_summary(), request_time)
582926
def log(self, request, spider):
        
        if self.debug:
            msg = "Filtered duplicate request: %(request)s"
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
        elif self.logdupes:
            msg = ("Filtered duplicate request %(request)s"
                   " - no more duplicates will be shown"
                   " (see DUPEFILTER_DEBUG to show all duplicates)")
            self.logger.debug(msg, {'request': request}, extra={'spider': spider})
            self.logdupes = False
1356147
def _log(self, name, element):  # pylint: disable=no-self-use
        
        from bs4 import BeautifulSoup, Tag
        if isinstance(element, Response):
            LOGGER.debug('%s response: URL=%s Code=%s', name, element.url, element.status_code)
        elif isinstance(element, (BeautifulSoup, Tag)):
            LOGGER.debug('%s HTML:\n%s', name, element)
57147
def _check_response_status(self, response):
        
        if response.status_code != requests.codes.ok:
            self._logger.error("%s %s", response.status_code, response.text)
            raise exceptions.RequestNonSuccessException(
                "Url {0} had status_code {1}".format(
                    response.url, response.status_code))
521621
def get_response(wsgi_request):
    '''
        
    '''
    service_start_time = datetime.now()
    # Get the view / handler for this request
    view, args, kwargs = resolve(wsgi_request.path_info)

    kwargs.update({"request": wsgi_request})

    # Let the view do his task.
    try:
        resp = view(*args, **kwargs)
    except Exception as exc:
        resp = HttpResponseServerError(content=exc.message)

    headers = dict(resp._headers.values())
    # Convert HTTP response into simple dict type.
    d_resp = {"status_code": resp.status_code, "reason_phrase": resp.reason_phrase,
              "headers": headers}
    try:
        d_resp.update({"body": resp.content})
    except ContentNotRenderedError:
        resp.render()
        d_resp.update({"body": resp.content})

    # Check if we need to send across the duration header.
    if _settings.ADD_DURATION_HEADER:
        d_resp['headers'].update({_settings.DURATION_HEADER_NAME: (datetime.now() - service_start_time).seconds})

    return d_resp
500956
def log_request(self, code='-', size='-'):
        #  pylint: disable=unused-argument
        
        self.log('%s: HTTP status %s',
                 (self._get_log_prefix(), code),
                 logging.INFO)
67226
def log_request(
        self, request: str, trim_log_values: bool = False, **kwargs: Any
    ) -> None:
        
        return log_(request, request_log, "info", trim=trim_log_values, **kwargs)