Python twisted.web.http.INTERNAL_SERVER_ERROR Examples

The following are 28 code examples of twisted.web.http.INTERNAL_SERVER_ERROR(). 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 twisted.web.http , or try the search function .
Example #1
Source File: server.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def processingFailed(self, reason):
        log.err(reason)
        if self.site.displayTracebacks:
            body = (b"<html><head><title>web.Server Traceback"
                    b" (most recent call last)</title></head>"
                    b"<body><b>web.Server Traceback"
                    b" (most recent call last):</b>\n\n" +
                    util.formatFailure(reason) +
                    b"\n\n</body></html>\n")
        else:
            body = (b"<html><head><title>Processing Failed"
                    b"</title></head><body>"
                    b"<b>Processing Failed</b></body></html>")

        self.setResponseCode(http.INTERNAL_SERVER_ERROR)
        self.setHeader(b'content-type', b"text/html")
        self.setHeader(b'content-length', intToBytes(len(body)))
        self.write(body)
        self.finish()
        return reason 
Example #2
Source File: server.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def processingFailed(self, reason):
        log.err(reason)
        if self.site.displayTracebacks:
            body = ("<html><head><title>web.Server Traceback (most recent call last)</title></head>"
                    "<body><b>web.Server Traceback (most recent call last):</b>\n\n"
                    "%s\n\n</body></html>\n"
                    % webutil.formatFailure(reason))
        else:
            body = ("<html><head><title>Processing Failed</title></head><body>"
                  "<b>Processing Failed</b></body></html>")

        self.setResponseCode(http.INTERNAL_SERVER_ERROR)
        self.setHeader('content-type',"text/html")
        self.setHeader('content-length', str(len(body)))
        self.write(body)
        self.finish()
        return reason 
Example #3
Source File: backup_account_resource.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def render_POST(self, request):
        account_recovery = AccountRecovery(
            self._authenticator.bonafide_session,
            self.soledad(request),
            self._service(request, '_leap_session').smtp_config,
            self._get_backup_email(request),
            self._leap_provider.server_name,
            language=self._get_language(request))

        def update_response(response):
            request.setResponseCode(NO_CONTENT)
            request.finish()

        def error_response(response):
            request.setResponseCode(INTERNAL_SERVER_ERROR)
            request.finish()

        d = account_recovery.update_recovery_code()
        d.addCallbacks(update_response, error_response)
        return NOT_DONE_YET 
Example #4
Source File: server.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def processingFailed(self, reason):
        log.err(reason)
        if self.site.displayTracebacks:
            body = ("<html><head><title>web.Server Traceback (most recent call last)</title></head>"
                    "<body><b>web.Server Traceback (most recent call last):</b>\n\n"
                    "%s\n\n</body></html>\n"
                    % webutil.formatFailure(reason))
        else:
            body = ("<html><head><title>Processing Failed</title></head><body>"
                  "<b>Processing Failed</b></body></html>")

        self.setResponseCode(http.INTERNAL_SERVER_ERROR)
        self.setHeader('content-type',"text/html")
        self.setHeader('content-length', str(len(body)))
        self.write(body)
        self.finish()
        return reason 
Example #5
Source File: twcgi.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def processEnded(self, reason):
        if reason.value.exitCode != 0:
            self._log.error("CGI {uri} exited with exit code {exitCode}",
                    uri=self.request.uri, exitCode=reason.value.exitCode)
        if self.errortext:
            self._log.error("Errors from CGI {uri}: {errorText}",
                uri=self.request.uri, errorText=self.errortext)
        if self.handling_headers:
            self._log.error("Premature end of headers in {uri}: {headerText}",
                uri=self.request.uri, headerText=self.headertext)
            self.request.write(
                resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                    "CGI Script Error",
                    "Premature end of script headers.").render(self.request))
        self.request.unregisterProducer()
        self.request.finish() 
Example #6
Source File: distrib.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def failed(self, failure):
        #XXX: Argh. FIXME.
        failure = str(failure)
        self.request.write(
            resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                               "Server Connection Lost",
                               "Connection to distributed server lost:" +
                               util._PRE(failure)).
            render(self.request))
        self.request.finish()
        self._log.info(failure) 
Example #7
Source File: twcgi.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def processEnded(self, reason):
        if reason.value.exitCode != 0:
            log.msg("CGI %s exited with exit code %s" %
                    (self.request.uri, reason.value.exitCode))
        if self.errortext:
            log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext))
        if self.handling_headers:
            log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext))
            self.request.write(
                error.ErrorPage(http.INTERNAL_SERVER_ERROR,
                                "CGI Script Error",
                                "Premature end of script headers.").render(self.request))
        self.request.unregisterProducer()
        self.request.finish() 
Example #8
Source File: distrib.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def failed(self, failure):
        #XXX: Argh. FIXME.
        failure = str(failure)
        self.request.write(
            error.ErrorPage(http.INTERNAL_SERVER_ERROR,
                            "Server Connection Lost",
                            "Connection to distributed server lost:" +
                            html.PRE(failure)).
            render(self.request))
        self.request.finish()
        log.msg(failure) 
Example #9
Source File: account_recovery_resource.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def render_POST(self, request):
        def success_response(response):
            request.setResponseCode(OK)
            request.finish()

        def error_response(failure):
            log.warn(failure)
            request.setResponseCode(INTERNAL_SERVER_ERROR)
            request.finish()

        d = self._handle_post(request)
        d.addCallbacks(success_response, error_response)
        return NOT_DONE_YET 
Example #10
Source File: __init__.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle_error_deferred(e, request):
    log.error(e)
    request.setResponseCode(INTERNAL_SERVER_ERROR)
    request.write('Something went wrong!')
    request.finish() 
Example #11
Source File: test_cgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_prematureEndOfHeaders(self):
        """
        If the process communicating with L{CGIProcessProtocol} ends before
        finishing writing out headers, the response has I{INTERNAL SERVER
        ERROR} as its status code.
        """
        request = DummyRequest([''])
        protocol = twcgi.CGIProcessProtocol(request)
        protocol.processEnded(failure.Failure(error.ProcessTerminated()))
        self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR) 
Example #12
Source File: twcgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def processEnded(self, reason):
        if reason.value.exitCode != 0:
            log.msg("CGI %s exited with exit code %s" %
                    (self.request.uri, reason.value.exitCode))
        if self.errortext:
            log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext))
        if self.handling_headers:
            log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext))
            self.request.write(
                resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                                   "CGI Script Error",
                                   "Premature end of script headers.").render(self.request))
        self.request.unregisterProducer()
        self.request.finish() 
Example #13
Source File: distrib.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def failed(self, failure):
        #XXX: Argh. FIXME.
        failure = str(failure)
        self.request.write(
            resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                               "Server Connection Lost",
                               "Connection to distributed server lost:" +
                               html.PRE(failure)).
            render(self.request))
        self.request.finish()
        log.msg(failure) 
Example #14
Source File: wsgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Call the WSGI application object, iterate it, and handle its output.

        This must be called in a non-I/O thread (ie, a WSGI application
        thread).
        """
        try:
            appIterator = self.application(self.environ, self.startResponse)
            for elem in appIterator:
                if elem:
                    self.write(elem)
                if self._requestFinished:
                    break
            close = getattr(appIterator, 'close', None)
            if close is not None:
                close()
        except:
            def wsgiError(started, type, value, traceback):
                err(Failure(value, type, traceback), "WSGI application error")
                if started:
                    self.request.transport.loseConnection()
                else:
                    self.request.setResponseCode(INTERNAL_SERVER_ERROR)
                    self.request.finish()
            self.reactor.callFromThread(wsgiError, self.started, *exc_info())
        else:
            def wsgiFinish(started):
                if not self._requestFinished:
                    if not started:
                        self._sendResponseHeaders()
                    self.request.finish()
            self.reactor.callFromThread(wsgiFinish, self.started)
        self.started = True 
Example #15
Source File: test_cgi.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_prematureEndOfHeaders(self):
        """
        If the process communicating with L{CGIProcessProtocol} ends before
        finishing writing out headers, the response has I{INTERNAL SERVER
        ERROR} as its status code.
        """
        request = DummyRequest([''])
        protocol = twcgi.CGIProcessProtocol(request)
        protocol.processEnded(failure.Failure(error.ProcessTerminated()))
        self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR) 
Example #16
Source File: request.py    From worker with GNU General Public License v3.0 5 votes vote down vote up
def delayed(f):
    def decorator(resource, request):
        @defer.inlineCallbacks
        def wrapper():
            try:
                yield f(resource, request)
            except Exception as e:
                log.error("Error in delayed decorator wrapped function: {e}", e=e)
                request.setResponseCode(http.INTERNAL_SERVER_ERROR)
                request.finish()
        wrapper()
        return server.NOT_DONE_YET
    return decorator 
Example #17
Source File: wsgi.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def run(self):
        """
        Call the WSGI application object, iterate it, and handle its output.

        This must be called in a non-I/O thread (ie, a WSGI application
        thread).
        """
        try:
            appIterator = self.application(self.environ, self.startResponse)
            for elem in appIterator:
                if elem:
                    self.write(elem)
                if self._requestFinished:
                    break
            close = getattr(appIterator, 'close', None)
            if close is not None:
                close()
        except:
            def wsgiError(started, type, value, traceback):
                self._log.failure(
                    "WSGI application error",
                    failure=Failure(value, type, traceback)
                )
                if started:
                    self.request.loseConnection()
                else:
                    self.request.setResponseCode(INTERNAL_SERVER_ERROR)
                    self.request.finish()
            self.reactor.callFromThread(wsgiError, self.started, *exc_info())
        else:
            def wsgiFinish(started):
                if not self._requestFinished:
                    if not started:
                        self._sendResponseHeaders()
                    self.request.finish()
            self.reactor.callFromThread(wsgiFinish, self.started)
        self.started = True 
Example #18
Source File: server.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def processingFailed(self, reason):
        """
        Finish this request with an indication that processing failed and
        possibly display a traceback.

        @param reason: Reason this request has failed.
        @type reason: L{twisted.python.failure.Failure}

        @return: The reason passed to this method.
        @rtype: L{twisted.python.failure.Failure}
        """
        self._log.failure('', failure=reason)
        if self.site.displayTracebacks:
            body = (b"<html><head><title>web.Server Traceback"
                    b" (most recent call last)</title></head>"
                    b"<body><b>web.Server Traceback"
                    b" (most recent call last):</b>\n\n" +
                    util.formatFailure(reason) +
                    b"\n\n</body></html>\n")
        else:
            body = (b"<html><head><title>Processing Failed"
                    b"</title></head><body>"
                    b"<b>Processing Failed</b></body></html>")

        self.setResponseCode(http.INTERNAL_SERVER_ERROR)
        self.setHeader(b'content-type', b"text/html")
        self.setHeader(b'content-length', intToBytes(len(body)))
        self.write(body)
        self.finish()
        return reason 
Example #19
Source File: _docker.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _remove_container(self, container_name):
        """
        Attempt to remove a container.

        Assumes the given container has already been stopped.

        :param unicode container_name: The fully-namespaced name of the
            container.
        :return: True if we removed the container, False otherwise.
        """
        try:
            # The ``docker.Client.stop`` method sometimes returns a
            # 404 error, even though the container exists.
            # See https://github.com/docker/docker/issues/13088
            # Wait until the container has actually stopped running
            # before attempting to remove it.  Otherwise we are
            # likely to see: 'docker.errors.APIError: 409 Client
            # Error: Conflict ("Conflict, You cannot remove a
            # running container. Stop the container before
            # attempting removal or use -f")'
            # This code should probably be removed once the above
            # issue has been resolved. See [FLOC-1850]
            self._client.wait(container_name)

            with start_action(
                action_type='flocker:docker:container_remove',
                container=container_name
            ):
                self._client.remove_container(container_name)
        except APIError as e:
            if e.response.status_code == NOT_FOUND:
                # If the container doesn't exist, we swallow the error,
                # since this method is supposed to be idempotent.
                return True
            elif e.response.status_code == INTERNAL_SERVER_ERROR:
                # Failure to remove container - see FLOC-3262 for an example.
                return False
            else:
                raise
        return True 
Example #20
Source File: _docker.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _stop_container(self, container_name):
        """Attempt to stop the given container.

        There is a race condition between a process dying and
        Docker noticing that fact:

        https://github.com/docker/docker/issues/5165#issuecomment-65753753

        If we get an error indicating that this race condition happened,
        return False. This means the caller should try again. If we *do*
        successfully stop the container, return True.

        :raise APIError: If the container failed to stop for some unknown
            reason.
        :return: True if we stopped the container, False otherwise.

        """
        try:
            with start_action(
                action_type='flocker:docker:container_stop',
                container=container_name
            ):
                self._client.stop(container_name)
        except APIError as e:
            if e.response.status_code == NOT_FOUND:
                # If the container doesn't exist, we swallow the error,
                # since this method is supposed to be idempotent.
                return True
            elif e.response.status_code == INTERNAL_SERVER_ERROR:
                # Docker returns this if the process had died, but
                # hasn't noticed it yet.
                return False
            else:
                raise
        return True 
Example #21
Source File: _docker.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _is_known_retryable(exception):
    """
    Determine if the text of a Docker 500 error represents a case which
    warrants an automatic retry.

    :param Exception exception: The exception from a ``docker.Client`` method
        call.

    :return bool: ``True`` if the exception represents a failure that is likely
        transient and a retry makes sense, ``False`` otherwise.
    """
    # A problem coming out of Docker itself
    if isinstance(exception, APIError):
        if exception.response.status_code == INTERNAL_SERVER_ERROR:
            error_text = exception.response.text
            return any(
                known in error_text
                for known
                in [
                    # https://github.com/docker/docker/issues/18194
                    u"Unknown device",
                    # https://github.com/docker/docker/issues/17653
                    u"no such device",
                ]
            )

    # A connection problem coming from the requests library used by docker-py
    if isinstance(exception, ConnectionError):
        if (
            len(exception.args) > 0 and
            isinstance(exception.args[0], ProtocolError)
        ):
            if (
                len(exception.args[0].args) > 1 and
                isinstance(exception.args[0].args[1], socket_error)
            ):
                return exception.args[0].args[1].errno in {ECONNREFUSED}

    return False 
Example #22
Source File: test_openstack.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_keystone_client_exception(self, logger):
        """
        ``keystoneclient.openstack.common.apiclient.exceptions.BadRequest`` is
        treated similarly to ``novaclient.exceptions.ClientException``.

        See ``test_novaclient_exception``.
        """
        response = Response()
        response._content = "hello world"
        result = KeystoneHttpError(
            message="Some things went wrong with some other things.",
            details={"key": "value"},
            response=response,
            request_id="abcdefghijklmnopqrstuvwxyz",
            url="/foo/bar",
            method="POST",
            http_status=INTERNAL_SERVER_ERROR,
        )
        logging_dummy = LoggingDummy(Dummy(result))
        self.assertRaises(KeystoneHttpError, logging_dummy.raise_method)

        logged = LoggedMessage.of_type(
            logger.messages, KEYSTONE_HTTP_ERROR,
        )[0]
        assertContainsFields(
            self, logged.message, {
                u"code": result.http_status,
                u"message": result.message,
                u"details": result.details,
                u"request_id": result.request_id,
                u"url": result.url,
                u"method": result.method,
                u"response": "hello world",
            },
        ) 
Example #23
Source File: test_openstack.py    From flocker with Apache License 2.0 5 votes vote down vote up
def test_novaclient_exception(self, logger):
        """
        The details of ``novaclient.exceptions.ClientException`` are logged
        when it is raised by the decorated method and the exception is still
        raised.
        """
        result = NovaClientException(
            code=INTERNAL_SERVER_ERROR,
            message="Some things went wrong with some other things.",
            details={"key": "value"},
            request_id="abcdefghijklmnopqrstuvwxyz",
            url="/foo/bar",
            method="POST",
        )
        logging_dummy = LoggingDummy(Dummy(result))
        self.assertRaises(NovaClientException, logging_dummy.raise_method)

        logged = LoggedMessage.of_type(
            logger.messages, NOVA_CLIENT_EXCEPTION,
        )[0]
        assertContainsFields(
            self, logged.message, {
                u"code": result.code,
                u"message": result.message,
                u"details": result.details,
                u"request_id": result.request_id,
                u"url": result.url,
                u"method": result.method,
            },
        ) 
Example #24
Source File: test_cgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_prematureEndOfHeaders(self):
        """
        If the process communicating with L{CGIProcessProtocol} ends before
        finishing writing out headers, the response has I{INTERNAL SERVER
        ERROR} as its status code.
        """
        request = DummyRequest([''])
        protocol = twcgi.CGIProcessProtocol(request)
        protocol.processEnded(failure.Failure(error.ProcessTerminated()))
        self.assertEqual(request.responseCode, INTERNAL_SERVER_ERROR) 
Example #25
Source File: twcgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def processEnded(self, reason):
        if reason.value.exitCode != 0:
            log.msg("CGI %s exited with exit code %s" %
                    (self.request.uri, reason.value.exitCode))
        if self.errortext:
            log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext))
        if self.handling_headers:
            log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext))
            self.request.write(
                resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                                   "CGI Script Error",
                                   "Premature end of script headers.").render(self.request))
        self.request.unregisterProducer()
        self.request.finish() 
Example #26
Source File: distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def failed(self, failure):
        #XXX: Argh. FIXME.
        failure = str(failure)
        self.request.write(
            resource.ErrorPage(http.INTERNAL_SERVER_ERROR,
                               "Server Connection Lost",
                               "Connection to distributed server lost:" +
                               util._PRE(failure)).
            render(self.request))
        self.request.finish()
        log.msg(failure) 
Example #27
Source File: wsgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        """
        Call the WSGI application object, iterate it, and handle its output.

        This must be called in a non-I/O thread (ie, a WSGI application
        thread).
        """
        try:
            appIterator = self.application(self.environ, self.startResponse)
            for elem in appIterator:
                if elem:
                    self.write(elem)
                if self._requestFinished:
                    break
            close = getattr(appIterator, 'close', None)
            if close is not None:
                close()
        except:
            def wsgiError(started, type, value, traceback):
                err(Failure(value, type, traceback), "WSGI application error")
                if started:
                    self.request.loseConnection()
                else:
                    self.request.setResponseCode(INTERNAL_SERVER_ERROR)
                    self.request.finish()
            self.reactor.callFromThread(wsgiError, self.started, *exc_info())
        else:
            def wsgiFinish(started):
                if not self._requestFinished:
                    if not started:
                        self._sendResponseHeaders()
                    self.request.finish()
            self.reactor.callFromThread(wsgiFinish, self.started)
        self.started = True 
Example #28
Source File: util.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def handleFailure(f, request=None):
    """
    Handle failure in callback chain, log and respond with traceback.

    See also:
    https://twistedmatrix.com/documents/16.0.0/core/howto/defer.html#errbacks
    """
    if f.type is Error:
        if request:
            request.setResponseCode(int(f.value.status))

        if hasattr(f.value, 'with_traceback'):
            f.with_traceback = f.value.with_traceback

        msg = None
        if isinstance(f.value.response, Failure):
            msg = f.value.response.getErrorMessage()
        elif type(f.value.response) in types.StringTypes:
            msg = f.value.response
        request.messages.append({'type': 'error', 'message': msg})

    else:
        if request:
            request.setResponseCode(http.INTERNAL_SERVER_ERROR)
            request.setHeader('Content-Type', 'text/plain; charset=utf-8')
        f.with_traceback = True

    if hasattr(f, 'with_traceback') and f.with_traceback:

        traceback = f.getTraceback()
        log.error(traceback)
        #f.trap(RuntimeError)
        request.write(traceback.encode('utf-8'))