Python pyramid.httpexceptions.HTTPException() Examples

The following are 6 code examples of pyramid.httpexceptions.HTTPException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyramid.httpexceptions , or try the search function .
Example #1
Source File: pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _capture_exception(exc_info):
    # type: (ExcInfo) -> None
    if exc_info[0] is None or issubclass(exc_info[0], HTTPException):
        return
    hub = Hub.current
    if hub.get_integration(PyramidIntegration) is None:
        return

    # If an integration is there, a client has to be there.
    client = hub.client  # type: Any

    event, hint = event_from_exception(
        exc_info,
        client_options=client.options,
        mechanism={"type": "pyramid", "handled": False},
    )

    hub.capture_event(event, hint=hint) 
Example #2
Source File: tweens.py    From shavar with Mozilla Public License 2.0 6 votes vote down vote up
def log_uncaught_exceptions(handler, registry):
    """Tween to log all uncaught exceptions."""

    def log_uncaught_exceptions_tween(request):
        try:
            return handler(request)
        except HTTPException:
            raise
        except Exception:
            lines = ["Uncaught exception while processing request:\n"]
            lines.append("%s %s\n" % (request.method, request.path_url))
            lines.append(safer_format_traceback(*sys.exc_info()))
            mozsvc.logger.error("".join(lines))
            raise

    return log_uncaught_exceptions_tween 
Example #3
Source File: decorators.py    From schematizer with Apache License 2.0 5 votes vote down vote up
def handle_view_exception(exception, status_code, error_message=None):
    def handle_view_exception_decorator(func):
        def handle_exception(request):
            try:
                return func(request)
            except exception as e:
                if not isinstance(e, HTTPException):
                    raise exception_response(
                        status_code,
                        detail=error_message or repr(e)
                    )
                else:
                    raise e
        return handle_exception
    return handle_view_exception_decorator 
Example #4
Source File: tweens.py    From shavar with Mozilla Public License 2.0 5 votes vote down vote up
def fuzz_backoff_headers(handler, registry):
    """Add some random fuzzing to the value of various backoff headers.

    This can help to avoid a "dogpile" effect where all backed-off clients
    retry at the same time and overload the server.
    """

    HEADERS = ["Retry-After", "X-Backoff", "X-Weave-Backoff"]

    def fuzz_response(response):
        for header in HEADERS:
            value = response.headers.get(header)
            if value is not None:
                # The header value is a backoff duration in seconds.  Fuzz
                # it upward by up to 5% or 5 seconds, whichever is greater.
                value = int(value)
                max_fuzz = max(int(value * 0.05), 5)
                value += random.randint(0, max_fuzz)
                response.headers[header] = str(value)

    def fuzz_backoff_headers_tween(request):
        try:
            response = handler(request)
        except HTTPException as response:
            fuzz_response(response)
            raise
        else:
            fuzz_response(response)
            return response

    return fuzz_backoff_headers_tween 
Example #5
Source File: tweens.py    From python-sensor with MIT License 4 votes vote down vote up
def __call__(self, request):
        ctx = tracer.extract(ot.Format.HTTP_HEADERS, request.headers)        
        scope = tracer.start_active_span('http', child_of=ctx)

        scope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
        scope.span.set_tag("http.host", request.host)
        scope.span.set_tag(ext.HTTP_METHOD, request.method)
        scope.span.set_tag(ext.HTTP_URL, request.path)

        if request.matched_route is not None:
            scope.span.set_tag("http.path_tpl", request.matched_route.pattern)

        if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
            for custom_header in agent.extra_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                h = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if h in request.headers:
                    scope.span.set_tag("http.%s" % custom_header, request.headers[h])

        if len(request.query_string):
            scrubbed_params = strip_secrets(request.query_string, agent.secrets_matcher, agent.secrets_list)
            scope.span.set_tag("http.params", scrubbed_params)

        response = None
        try:
            response = self.handler(request)
            
            tracer.inject(scope.span.context, ot.Format.HTTP_HEADERS, response.headers)
            response.headers['Server-Timing'] = "intid;desc=%s" % scope.span.context.trace_id
        except HTTPException as e:
            response = e
            raise
        except BaseException as e:
            scope.span.set_tag("http.status", 500)

            # we need to explicitly populate the `message` tag with an error here
            # so that it's picked up from an SDK span
            scope.span.set_tag("message", str(e))            
            scope.span.log_exception(e)
            
            logger.debug("Pyramid Instana tween", exc_info=True)
        finally:
            if response:
                scope.span.set_tag("http.status", response.status_int)
                
                if 500 <= response.status_int <= 511:
                    if response.exception is not None:
                        message = str(response.exception)
                        scope.span.log_exception(response.exception)
                    else:
                        message = response.status
                        
                    scope.span.set_tag("message", message)
                    scope.span.assure_errored()

            scope.close()

        return response 
Example #6
Source File: tweens.py    From shavar with Mozilla Public License 2.0 4 votes vote down vote up
def send_backoff_responses(handler, registry):
    """Send backoff/unavailable responses to a percentage of clients.

    This tween allows the server to respond to a set percentage of traffic with
    an X-Backoff header and/or a "503 Service Unavilable" response.  The two
    probabilities are controlled by config options 'mozsvc.backoff_probability'
    and 'mozsvc.unavailable_probability' respectively.  If neither option is
    set then the tween is not activated, avoiding overhead in the (hopefully!)
    common case.
    """
    settings = registry.settings
    backoff_probability = settings.get("mozsvc.backoff_probability", 0)
    unavailable_probability = settings.get("mozsvc.unavailable_probability", 0)
    retry_after = settings.get("mozsvc.retry_after", 1800)

    if backoff_probability:

        backoff_probability = float(backoff_probability)

        def add_backoff_header(response):
            if "X-Backoff" not in response.headers:
                if "X-Weave-Backoff" not in response.headers:
                    response.headers["X-Backoff"] = str(retry_after)
                    response.headers["X-Weave-Backoff"] = str(retry_after)

        def send_backoff_header_tween(request, handler=handler):
            try:
                response = handler(request)
            except HTTPException as response:
                if random.random() < backoff_probability:
                    add_backoff_header(response)
                raise
            else:
                if random.random() < backoff_probability:
                    add_backoff_header(response)
                return response

        handler = send_backoff_header_tween

    if unavailable_probability:

        unavailable_probability = float(unavailable_probability)

        def send_unavailable_response_tween(request, handler=handler):
            if random.random() < unavailable_probability:
                return HTTPServiceUnavailable(body="0",
                                              retry_after=retry_after,
                                              content_type="application/json")
            return handler(request)

        handler = send_unavailable_response_tween

    return handler