コード例 #1
0
ファイル: grid_openid.py プロジェクト: heromod/migrid
    def do_GET(self):
        """Handle all HTTP GET requests"""
        try:
            self.parsed_uri = urlparse(self.path)
            self.query = {}
            for (key, val) in cgi.parse_qsl(self.parsed_uri[4]):
                # print "DEBUG: checking input arg %s: '%s'" % (key, val)
                validate_helper = self.validators.get(key, invalid_argument)
                # Let validation errors pass to general exception handler below
                validate_helper(val)
                self.query[key] = val

            self.setUser()

            # print "DEBUG: checking path '%s'" % self.parsed_uri[2]
            valid_path(self.parsed_uri[2])
            path = self.parsed_uri[2]

            # Strip server_base before testing location
            path = path.replace("%s/" % self.server.server_base, '', 1)

            if path == '/':
                self.showMainPage()
            elif path.startswith('/ping'):
                self.showPingPage()
            elif path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/login':
                self.showLoginPage('/%s/' % self.server.server_base,
                                   '/%s/' % self.server.server_base)
            elif path == '/loginsubmit':
                self.doLogin()
            elif path.startswith('/id/'):
                self.showIdPage(path)
            elif path.startswith('/yadis/'):
                self.showYadis(path[7:])
            elif path == '/serveryadis':
                self.showServerYadis()
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
            print "ERROR: %s" % cgitb.html(sys.exc_info(), context=10)
コード例 #2
0
ファイル: wsgilog.py プロジェクト: spawn3/uss
 def catch(self, environ, start_response):
     '''Exception catcher.'''
     # Log exception
     if self.log: self.logger.exception(self.message)
     # Debug
     if self.debug: pdb.pm()
     # Write HTML-formatted exception tracebacks to a file
     if self.htmlfile is not None:
         open(self.htmlfile, 'wb').write(html(sys.exc_info()))
     # Send HTML-formatted exception tracebacks to the browser
     if self.tohtml:
         start_response(HTTPMSG, [('Content-type', 'text/html')])
         return [html(sys.exc_info())]
     # Return error handler
     return self._errapp(environ, start_response)
コード例 #3
0
ファイル: __init__.py プロジェクト: dvdotsenko/ges
 def catch(self, environ, start_response):
     '''Exception catcher.'''
     # Log exception
     if self.log: self.logger.exception(self.message)
     # Debug
     if self.debug: pdb.pm()
     # Write HTML-formatted exception tracebacks to a file
     if self.htmlfile is not None:
         open(self.htmlfile, 'wb').write(html(sys.exc_info()))
     # Send HTML-formatted exception tracebacks to the browser
     if self.tohtml:
         start_response(HTTPMSG, [('Content-type', 'text/html')])
         return [html(sys.exc_info())]
     # Return error handler
     return self._errapp(environ, start_response)
コード例 #4
0
ファイル: server.py プロジェクト: abtain/Heraldry
    def do_GET(self):
        try:
            self.parsed_uri = urlparse(self.path)
            self.query = {}
            for k, v in cgi.parse_qsl(self.parsed_uri[4]):
                self.query[k] = v

            self.setUser()

            path = self.parsed_uri[2].lower()

            if path == '/':
                self.showMainPage()
            elif path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/login':
                self.showLoginPage('/', '/')
            elif path == '/loginsubmit':
                self.doLogin()
            else:
                self.showIdPage(path)

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #5
0
ファイル: servlet.py プロジェクト: graingert/overblock
    def __call_service(self, query):
        """Execute service method implemented by child class.

        When either a GET or POST request is received, this method is
        called with a string representing the query. Request and response
        objects are created for the child's service method, and an answer
        is sent back to the client with errors automatically being caught."""
        request = _HttpServletRequest(query)
        response = _HttpServletResponse()
        try:
            self.service(request, response)
        except Exception:
            if self.__debug:
                self.send_response(500)
                self.send_header('Content-Type', 'text/html')
                self.send_header('Connection', 'close')
                self.end_headers()
                klass, value, trace = sys.exc_info()

                print 'trace:',trace

                # The next function call may raise an exception.
                html = cgitb.html((klass, value, trace.tb_next))
                self.wfile.write(html.encode())
            else:
                self.send_error(500)
        else:
            response_value = response._value
            self.send_response(200)
            self.send_header('Content-Type', response._type)
            self.send_header('Content-Length', str(len(response_value)))
            self.end_headers()
            self.wfile.write(response_value)
コード例 #6
0
ファイル: server.py プロジェクト: ziima/python-openid
    def do_GET(self):
        try:
            self.parsed_uri = urlparse(self.path)
            self.query = {}
            for k, v in parse_qsl(self.parsed_uri[4]):
                self.query[k] = v

            self.setUser()

            path = self.parsed_uri[2].lower()

            if path == '/':
                self.showMainPage()
            elif path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/login':
                self.showLoginPage('/', '/')
            elif path == '/loginsubmit':
                self.doLogin()
            elif path.startswith('/id/'):
                self.showIdPage(path)
            elif path.startswith('/yadis/'):
                self.showYadis(path[7:])
            elif path == '/serveryadis':
                self.showServerYadis()
            else:
                self.send_response(404)
                self.end_headers()

        except Exception:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #7
0
ファイル: ParseTornado.py プロジェクト: jfly/TornadoTracker
    def generateHtml(self, einfo=None):
        index = open(self.htmlFile, "w")
        index.write(
            """<html>
<body>
"""
        )
        for i, (description, images) in enumerate(self.steps):
            stepNumber = i + 1

            index.write("<h2>%s. %s</h2>\n" % (stepNumber, description))
            for nthImage, image in enumerate(images):
                absoluteImageFileName = self.stepImage(stepNumber, nthImage)
                relativeImageFileName = os.path.basename(absoluteImageFileName)
                index.write("<img src='%s'/>\n" % (relativeImageFileName))
                image.save(absoluteImageFileName)

        if einfo:
            index.write(cgitb.html(einfo))

        index.write(
            """
</body>
</html>
"""
        )
        index.close()
コード例 #8
0
ファイル: message.py プロジェクト: anonmily/pythonlib
	def notify_error(self):
		ex_type, ex, tb = sys.exc_info()
		self.send_html({ 
			'subject': 'Fatal Error',
			'html': cgitb.html(sys.exc_info()),
			'text': cgitb.text(sys.exc_info())
		})
コード例 #9
0
    def __call_service(self, query):
        """Execute service method implemented by child class.

        When either a GET or POST request is received, this method is
        called with a string representing the query. Request and response
        objects are created for the child's service method, and an answer
        is sent back to the client with errors automatically being caught."""
        request = _HttpServletRequest(query)
        response = _HttpServletResponse()
        # noinspection PyBroadException
        try:
            self.service(request, response)
        except Exception:
            if self.__debug:
                self.send_response(500)
                self.send_header('Content-Type', 'text/html')
                self.send_header('Connection', 'close')
                self.end_headers()
                klass, value, trace = sys.exc_info()
                # The next function call may raise an exception.
                html = cgitb.html((klass, value, trace.tb_next))
                self.wfile.write(html.encode())
            else:
                self.send_error(500)
        else:
            self.__send_response(response)
コード例 #10
0
 def test_html(self):
     try:
         raise ValueError('Hello World')
     except ValueError as err:
         html = cgitb.html(sys.exc_info())
         self.assertIn('ValueError', html)
         self.assertIn(str(err), html)
コード例 #11
0
ファイル: fcgiserver.py プロジェクト: bharathi26/pycopia
def ErrorHandler(exc_info, stream):
    import cgitb
    stream.write('Status: 500 fcgi error\r\n')
    stream.write('Content-Type: text/html\r\n')
    stream.write('\r\n')
    stream.write(cgitb.html(exc_info))
    stream.flush()
コード例 #12
0
def send_exception_email(emailtype):
    """
    If we decide to capture exceptions we can call
    this to send well formated emails out with
    error data and location in the script
    """
    if emailtype == 'exception':
        try:
            if CFG.values['emailexceptions'] and CFG.values[
                    'emailexceptionsrecipient']:
                import cgitb
                emaildata = {
                    "emailtitle": "EMR Script Exception Error",
                    "date": date.today().strftime('%d, %b %Y'),
                    "exceptionhtml": cgitb.html(sys.exc_info())
                }

                EMAIL.send_email_template(
                    jinjatemplate='email-html_exception',
                    jinjadata=emaildata,
                    subject="EMR Script Exception Error",
                    recipients=str(
                        CFG.values['emailexceptionsrecipient']).split(';'))
        except:
            pass
コード例 #13
0
    def _actionGenericDoDelOld(self, oCoreObjectLogic, sCoreObjectIdFieldName, sRedirectAction):
        """
        Delete entry (using oLogicType.remove).

        @param oCoreObjectLogic         A *Logic class

        @param sCoreObjectIdFieldName   Name of HTTP POST variable that
                                        contains object ID information

        @param sRedirectAction          An action for redirect user to
                                        in case of operation success
        """
        iCoreDataObjectId = self.getStringParam(sCoreObjectIdFieldName) # STRING?!?!
        self._checkForUnknownParameters()

        try:
            self._sPageTitle  = None
            self._sPageBody   = None
            self._sRedirectTo = self._sActionUrlBase + sRedirectAction
            return oCoreObjectLogic(self._oDb).remove(self._oCurUser.uid, iCoreDataObjectId)
        except Exception as oXcpt:
            self._oDb.rollback();
            self._sPageTitle  = 'Unable to delete record'
            self._sPageBody   = str(oXcpt);
            if config.g_kfDebugDbXcpt:
                self._sPageBody += cgitb.html(sys.exc_info());
            self._sRedirectTo = None

        return False
コード例 #14
0
ファイル: server.py プロジェクト: The-Actual-Damien/openid
    def do_GET(self):
        try:
            self.parsed_uri = urlparse(self.path)
            self.query = {}
            for k, v in parse_qsl(self.parsed_uri[4]):
                self.query[k] = v

            self.setUser()

            path = self.parsed_uri[2].lower()

            if path == '/':
                self.showMainPage()
            elif path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/login':
                self.showLoginPage('/', '/')
            elif path == '/loginsubmit':
                self.doLogin()
            elif path.startswith('/id/'):
                self.showIdPage(path)
            elif path.startswith('/yadis/'):
                self.showYadis(path[7:])
            elif path == '/serveryadis':
                self.showServerYadis()
            else:
                self.send_response(404)
                self.end_headers()

        except Exception:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #15
0
ファイル: server.py プロジェクト: jefftriplett/python-openid
    def do_POST(self):
        try:
            self.parsed_uri = urlparse(self.path)

            self.setUser()
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)

            self.query = {}
            for k, v in cgi.parse_qsl(post_data):
                self.query[k] = v

            path = self.parsed_uri[2]
            if path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/allow':
                self.handleAllow(self.query)
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #16
0
ファイル: wuibase.py プロジェクト: svn2github/virtualbox
    def _actionGenericDoRemove(self, oLogicType, sParamId, sRedirAction):
        """
        Delete entry (using oLogicType.removeEntry).

        oLogicType is a class that implements addEntry.

        sParamId is the name (ksParam_...) of the HTTP variable hold the ID of
        the database entry to delete.

        sRedirAction is what action to redirect to on success.
        """
        import cgitb;

        idEntry = self.getIntParam(sParamId, iMin = 1, iMax = 0x7ffffffe)
        fCascade = self.getBoolParam('fCascadeDelete', False);
        sRedirectTo = self.getRedirectToParameter(self._sActionUrlBase + sRedirAction);
        self._checkForUnknownParameters()

        try:
            self._sPageTitle  = None
            self._sPageBody   = None
            self._sRedirectTo = sRedirectTo;
            return oLogicType(self._oDb).removeEntry(self._oCurUser.uid, idEntry, fCascade = fCascade, fCommit = True);
        except Exception as oXcpt:
            self._oDb.rollback();
            self._sPageTitle  = 'Unable to delete entry';
            self._sPageBody   = str(oXcpt);
            if config.g_kfDebugDbXcpt:
                self._sPageBody += cgitb.html(sys.exc_info());
            self._sRedirectTo = None;
        return False;
コード例 #17
0
ファイル: wuibase.py プロジェクト: AndSecYi/LLDBagility
    def _actionGenericDoRemove(self, oLogicType, sParamId, sRedirAction):
        """
        Delete entry (using oLogicType.removeEntry).

        oLogicType is a class that implements addEntry.

        sParamId is the name (ksParam_...) of the HTTP variable hold the ID of
        the database entry to delete.

        sRedirAction is what action to redirect to on success.
        """
        import cgitb;

        idEntry = self.getIntParam(sParamId, iMin = 1, iMax = 0x7ffffffe)
        fCascade = self.getBoolParam('fCascadeDelete', False);
        sRedirectTo = self.getRedirectToParameter(self._sActionUrlBase + sRedirAction);
        self._checkForUnknownParameters()

        try:
            if self.isReadOnlyUser():
                raise Exception('"%s" is a read only user!' % (self._oCurUser.sUsername,));
            self._sPageTitle  = None
            self._sPageBody   = None
            self._sRedirectTo = sRedirectTo;
            return oLogicType(self._oDb).removeEntry(self._oCurUser.uid, idEntry, fCascade = fCascade, fCommit = True);
        except Exception as oXcpt:
            self._oDb.rollback();
            self._sPageTitle  = 'Unable to delete entry';
            self._sPageBody   = str(oXcpt);
            if config.g_kfDebugDbXcpt:
                self._sPageBody += cgitb.html(sys.exc_info());
            self._sRedirectTo = None;
        return False;
コード例 #18
0
    def do_POST(self):
        try:
            self.parsed_uri = urlparse(self.path)

            self.setUser()
            content_length = int(self.headers["Content-Length"])
            post_data = self.rfile.read(content_length)

            self.query = {}
            self.genurl = {}
            for k, v in cgi.parse_qsl(post_data):
                self.query[k] = v

            path = self.parsed_uri[2]
            if path == "/openidserver":
                self.serverEndPoint(self.query)

            elif path == "/allow":
                self.handleAllow(self.query)
            elif path == "/signin":
                self.handleSignin(self.query)
            elif path == "/invalid":
                self.send_response(404)
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #19
0
ファイル: __init__.py プロジェクト: marcv/pyramid_errmail
 def errmail_tween(request, subject=subject):
     try:
         return handler(request)
     except Exception, e:
         try:
             exc_info = sys.exc_info()
             mailer = get_mailer(request)
             exc_repr = repr(e)[:200]
             localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
             gmtime = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
             mapping = {'localtime':localtime,
                        'gmtime':gmtime,
                        'hostname':hostname,
                        'exception':exc_repr}
             def replace(match):
                 whole, param1, param2 = match.groups()
                 return mapping.get(param1 or param2, whole)
             subject = _interp_regex.sub(replace, subject)
             html = cgitb.html(exc_info)
             header = request.url
             html = '<html><h1>%s</h1>%s</html>' % (header, html)
             body = ''.join(traceback.format_exception(*exc_info))
             body = '%s\n\n%s' % (header, body)
             message = Message(subject=subject,
                               sender=sender,
                               recipients=recipients,
                               html=html,
                               body=body)
             mailer.send_immediately(message, fail_silently=True)
             raise
         finally:
             del exc_info
コード例 #20
0
ファイル: wuiadmin.py プロジェクト: susanych1234/virtualbox
    def _actionGenericDoDelOld(self, oCoreObjectLogic, sCoreObjectIdFieldName,
                               sRedirectAction):
        """
        Delete entry (using oLogicType.remove).

        @param oCoreObjectLogic         A *Logic class

        @param sCoreObjectIdFieldName   Name of HTTP POST variable that
                                        contains object ID information

        @param sRedirectAction          An action for redirect user to
                                        in case of operation success
        """
        iCoreDataObjectId = self.getStringParam(
            sCoreObjectIdFieldName)  # STRING?!?!
        self._checkForUnknownParameters()

        try:
            self._sPageTitle = None
            self._sPageBody = None
            self._sRedirectTo = self._sActionUrlBase + sRedirectAction
            return oCoreObjectLogic(self._oDb).remove(self._oCurUser.uid,
                                                      iCoreDataObjectId)
        except Exception as oXcpt:
            self._oDb.rollback()
            self._sPageTitle = 'Unable to delete record'
            self._sPageBody = str(oXcpt)
            if config.g_kfDebugDbXcpt:
                self._sPageBody += cgitb.html(sys.exc_info())
            self._sRedirectTo = None

        return False
コード例 #21
0
def ErrorHandler(exc_info, stream):
    import cgitb
    stream.write('Status: 500 fcgi error\r\n')
    stream.write('Content-Type: text/html\r\n')
    stream.write('\r\n')
    stream.write(cgitb.html(exc_info))
    stream.flush()
コード例 #22
0
ファイル: auth.py プロジェクト: batwalrus76/ubertool_src
    def post(self):
        try:
            #print "in OpenID AUth service post with request: "
            #print self.request
            self.path = self.request.url
            self.parsed_uri = urlparse(self.path)

            self.setUser()
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)

            self.query = {}
            for k, v in cgi.parse_qsl(post_data):
                self.query[k] = v
            print self.query
            path = self.parsed_uri[2]
            if path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/allow':
                self.handleAllow(self.query)
            else:
                self.response.status ='404 Not Found'

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #23
0
def show_error_web(exc_info):
    try:
        html = cgitb.html(exc_info)
        with NamedTemporaryFile(delete=False, mode='w',
                                suffix='.html') as tmp_file:
            tmp_file.write(html)
            webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
    except BaseException:
        # Oof. This happens sometimes with some exceptions ("AttributeError: characters_written").
        try:
            html = cgitb.text(exc_info)
            with NamedTemporaryFile(delete=False, mode='w',
                                    suffix='.txt') as tmp_file:
                tmp_file.write(html)
                webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
        except BaseException:
            # Hm... now it's getting ridiculous.
            try:
                html = ''.join(traceback.format_exception(*exc_info))
                with NamedTemporaryFile(delete=False, mode='w',
                                        suffix='.txt') as tmp_file:
                    tmp_file.write(html)
                    webbrowser.open_new_tab(Path(tmp_file.name).as_uri())
            except BaseException:
                # Yikes!
                md = SkyTempleMessageDialog(
                    None,
                    Gtk.DialogFlags.DESTROY_WITH_PARENT,
                    Gtk.MessageType.ERROR,
                    Gtk.ButtonsType.OK,
                    _("Trying to display the error failed. Wow!"),
                    title=":(")
                md.run()
                md.destroy()
コード例 #24
0
ファイル: server.py プロジェクト: thomir/python3-openid
    def do_POST(self):
        try:
            self.parsed_uri = urlparse(self.path)

            self.setUser()
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)

            self.query = {}
            for k, v in cgi.parse_qsl(post_data):
                self.query[k] = v

            path = self.parsed_uri[2]
            if path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/allow':
                self.handleAllow(self.query)
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(
                bytes(cgitb.html(sys.exc_info(), context=10), 'utf-8'))
コード例 #25
0
 def handleException(self, path, params, post_params):
     self.sendResponse(500)
     self.send_header('Content-type', 'text/html')
     self.end_headers()
     msg = cgitb.html(sys.exc_info(), context=10)
     print msg
     # TODO. Not display the error message.
     self.wfile.write(msg)
コード例 #26
0
 def error(self, req):
     """
     Called by Request if an exception occurs within the handler. May and
     should be overridden.
     """
     import cgitb
     req.stdout.write('Content-Type: text/html\r\n\r\n' +
                      cgitb.html(sys.exc_info()))
コード例 #27
0
ファイル: ajp_base.py プロジェクト: cwallenpoole/blog_m3
 def error(self, request):
     """
     Override to provide custom error handling. Ideally, however,
     all errors should be caught at the application level.
     """
     request.startResponse(200, 'OK', [('Content-Type', 'text/html')])
     import cgitb
     request.write(cgitb.html(sys.exc_info()))
コード例 #28
0
ファイル: ashttpcommon.py プロジェクト: yuliang-leon/exp
	def handleException(self, path, params, post_params):
		self.sendResponse(500)
		self.send_header('Content-type', 'text/html')
		self.end_headers()
		msg = cgitb.html(sys.exc_info(), context=10)
		print msg
		# TODO. Not display the error message.
		self.wfile.write(msg)
コード例 #29
0
ファイル: _fcgi.py プロジェクト: nyuhuhuu/trachacks
    def error(self, req):
        """
        Called by Request if an exception occurs within the handler. May and
        should be overridden.
        """
        import cgitb

        req.stdout.write("Content-Type: text/html\r\n\r\n" + cgitb.html(sys.exc_info()))
コード例 #30
0
ファイル: scgi_base.py プロジェクト: ivanov/sycamore
 def error(self, request):
     """
     Override to provide custom error handling. Ideally, however,
     all errors should be caught at the application level.
     """
     import cgitb
     request.stdout.write('Content-Type: text/html\r\n\r\n' +
                          cgitb.html(sys.exc_info()))
コード例 #31
0
    def except_handler(etype=None, evalue=None, etb=None):
        """
        Log uncaught exceptions and display a friendly error.
        """
        if not etype or not evalue or not etb:
            etype, evalue, etb = sys.exc_info()
        import cgitb
        out(cgitb.reset())
        if logdir is None:
            out(error_template % """
    A problem has occurred, but it probably isn't your fault.
    """)
        else:
            import stat
            import traceback
            try:
                doc = cgitb.html((etype, evalue, etb), 5)
            except:  # just in case something goes wrong
                doc = ''.join(traceback.format_exception(etype, evalue, etb))
            if debug:
                out(doc)
                return
            try:
                while etb.tb_next != None:
                    etb = etb.tb_next
                e_file = etb.tb_frame.f_code.co_filename
                e_line = etb.tb_frame.f_lineno
                ldir = os.path.join(logdir, os.path.split(e_file)[-1])
                if not os.path.exists(ldir):
                    os.umask(0000)
                    os.makedirs(ldir)
                (fd, path) = tempfile.mkstemp(prefix="%s_" % e_line,
                                              suffix='.html',
                                              dir=ldir)
                fh = os.fdopen(fd, 'w')
                fh.write(doc)
                fh.close()
                os.chmod(path, stat.S_IROTH)
                out(error_template % """\
A problem has occurred, but it probably isn't your fault.
RED has remembered it, and we'll try to fix it soon.""")
            except:
                out(error_template % """\
A problem has occurred, but it probably isn't your fault.
RED tried to save it, but it couldn't! Oops.<br>
Please e-mail the information below to
<a href='mailto:[email protected]'>[email protected]</a>
and we'll look into it.""")
                out("<h3>Original Error</h3>")
                out("<pre>")
                out(''.join(traceback.format_exception(etype, evalue, etb)))
                out("</pre>")
                out("<h3>Write Error</h3>")
                out("<pre>")
                etype, value, tb = sys.exc_info()
                out(''.join(traceback.format_exception(etype, value, tb)))
                out("</pre>")
        sys.exit(1)  # We're in an uncertain state, so we must die horribly.
コード例 #32
0
    def errorPage(self, sError, aXcptInfo, sLogFile = None):
        """
        Displays a page with an error message.
        """
        if sLogFile is not None:
            self.errorLog(sError, aXcptInfo, sLogFile);

        # Reset buffering, hoping that nothing was flushed yet.
        self._sBodyType = None;
        self._sHtmlBody = '';
        self._cchCached = 0;
        if not self._fHeaderWrittenOut:
            if self._fHtmlDebugOutput:
                self.setHeaderField('Content-Type', 'text/html; charset=utf-8');
            else:
                self.setHeaderField('Content-Type', 'text/plain; charset=utf-8');

        # Write the error page.
        if self._fHtmlDebugOutput:
            self.write('<html><head><title>Test Manage Error</title></head>\n' +
                       '<body><h1>Test Manager Error:</h1>\n' +
                       '<p>' + sError + '</p>\n');
        else:
            self.write(' Test Manage Error\n'
                       '===================\n'
                       '\n'
                       '' + sError + '\n\n');

        if aXcptInfo[0] is not None:
            if self._fHtmlDebugOutput:
                self.write('<h1>Backtrace:</h1>\n');
                self.write(cgitb.html(aXcptInfo, 5));
            else:
                self.write('Backtrace\n'
                           '---------\n'
                           '\n');
                self.write(cgitb.text(aXcptInfo, 5));
                self.write('\n\n');

        if self.kfDebugInfoEnabled:
            if self._fHtmlDebugOutput:
                self.write('<h1>Debug Info:</h1>\n');
            else:
                self.write('Debug Info\n'
                           '----------\n'
                           '\n');
            self.debugDumpStuff();

            for fn in self._afnDebugInfo:
                try:
                    fn(self, self._fHtmlDebugOutput);
                except Exception as oXcpt:
                    self.write('\nDebug info callback %s raised exception: %s\n' % (fn, oXcpt));

        if self._fHtmlDebugOutput:
            self.write('</body></html>');

        self.flush();
コード例 #33
0
    def errorPage(self, sError, aXcptInfo, sLogFile = None):
        """
        Displays a page with an error message.
        """
        if sLogFile is not None:
            self.errorLog(sError, aXcptInfo, sLogFile);

        # Reset buffering, hoping that nothing was flushed yet.
        self._sBodyType = None;
        self._sHtmlBody = '';
        self._cchCached = 0;
        if not self._fHeaderWrittenOut:
            if self._fHtmlDebugOutput:
                self.setHeaderField('Content-Type', 'text/html; charset=utf-8');
            else:
                self.setHeaderField('Content-Type', 'text/plain; charset=utf-8');

        # Write the error page.
        if self._fHtmlDebugOutput:
            self.write('<html><head><title>Test Manage Error</title></head>\n' +
                       '<body><h1>Test Manager Error:</h1>\n' +
                       '<p>' + sError + '</p>\n');
        else:
            self.write(' Test Manage Error\n'
                       '===================\n'
                       '\n'
                       '' + sError + '\n\n');

        if aXcptInfo[0] is not None:
            if self._fHtmlDebugOutput:
                self.write('<h1>Backtrace:</h1>\n');
                self.write(cgitb.html(aXcptInfo, 5));
            else:
                self.write('Backtrace\n'
                           '---------\n'
                           '\n');
                self.write(cgitb.text(aXcptInfo, 5));
                self.write('\n\n');

        if self.kfDebugInfoEnabled:
            if self._fHtmlDebugOutput:
                self.write('<h1>Debug Info:</h1>\n');
            else:
                self.write('Debug Info\n'
                           '----------\n'
                           '\n');
            self.debugDumpStuff();

            for fn in self._afnDebugInfo:
                try:
                    fn(self, self._fHtmlDebugOutput);
                except Exception as oXcpt:
                    self.write('\nDebug info callback %s raised exception: %s\n' % (fn, oXcpt));

        if self._fHtmlDebugOutput:
            self.write('</body></html>');

        self.flush();
コード例 #34
0
ファイル: webui.py プロジェクト: collizo4sky/redbot
    def except_handler(etype=None, evalue=None, etb=None):
        """
        Log uncaught exceptions and display a friendly error.
        """
        if not etype or not evalue or not etb:
            etype, evalue, etb = sys.exc_info()
        import cgitb
        out(cgitb.reset())
        if logdir is None:
            out(error_template % """
    A problem has occurred, but it probably isn't your fault.
    """)
        else:
            import stat
            import traceback
            try:
                doc = cgitb.html((etype, evalue, etb), 5)
            except:                  # just in case something goes wrong
                doc = ''.join(traceback.format_exception(etype, evalue, etb))
            if debug:
                out(doc)
                return
            try:
                while etb.tb_next != None:
                    etb = etb.tb_next
                e_file = etb.tb_frame.f_code.co_filename
                e_line = etb.tb_frame.f_lineno
                ldir = os.path.join(logdir, os.path.split(e_file)[-1])
                if not os.path.exists(ldir):
                    os.umask(0000)
                    os.makedirs(ldir)
                (fd, path) = tempfile.mkstemp(
                    prefix="%s_" % e_line, suffix='.html', dir=ldir
                )
                fh = os.fdopen(fd, 'w')
                fh.write(doc)
                fh.close()
                os.chmod(path, stat.S_IROTH)
                out(error_template % """\
A problem has occurred, but it probably isn't your fault.
RED has remembered it, and we'll try to fix it soon.""")
            except:
                out(error_template % """\
A problem has occurred, but it probably isn't your fault.
RED tried to save it, but it couldn't! Oops.<br>
Please e-mail the information below to
<a href='mailto:[email protected]'>[email protected]</a>
and we'll look into it.""")
                out("<h3>Original Error</h3>")
                out("<pre>")
                out(''.join(traceback.format_exception(etype, evalue, etb)))
                out("</pre>")
                out("<h3>Write Error</h3>")
                out("<pre>")
                etype, value, tb = sys.exc_info()
                out(''.join(traceback.format_exception(etype, value, tb)))
                out("</pre>")
        sys.exit(1) # We're in an uncertain state, so we must die horribly.
コード例 #35
0
ファイル: __init__.py プロジェクト: jbq/Romero
	def handleRequest(self):
		try:
			value = self.processRequest()
			self._startResponse(self.status, self.headers)	
			return value
		except:
			import cgitb
			self._startResponse("500 Internal Server Error", [('Content-Type', 'text/html')])
			return cgitb.html(sys.exc_info())
コード例 #36
0
ファイル: test_cgitb.py プロジェクト: 0jpq0/kbengine
 def test_html(self):
     try:
         raise ValueError("Hello World")
     except ValueError as err:
         # If the html was templated we could do a bit more here.
         # At least check that we get details on what we just raised.
         html = cgitb.html(sys.exc_info())
         self.assertIn("ValueError", html)
         self.assertIn(str(err), html)
コード例 #37
0
 def test_html(self):
     try:
         raise ValueError("Hello World")
     except ValueError as err:
         # If the html was templated we could do a bit more here.
         # At least check that we get details on what we just raised.
         html = cgitb.html(sys.exc_info())
         self.assertIn("ValueError", html)
         self.assertIn(str(err), html)
コード例 #38
0
def application(environ, start_response):
    """
    Entry point for wsgi.
    """
    ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues>
    req = SimulatedModPythonRequest(environ, start_response)
    #print 'Starting mod_python simulation'
    try:
        try:
            possible_module, possible_handler = is_mp_legacy_publisher_path(
                environ['PATH_INFO'])
            if possible_module is not None:
                mp_legacy_publisher(req, possible_module, possible_handler)
            elif CFG_WSGI_SERVE_STATIC_FILES:
                possible_static_path = is_static_path(environ['PATH_INFO'])
                if possible_static_path is not None:
                    from invenio.bibdocfile import stream_file
                    stream_file(req, possible_static_path)
                else:
                    ret = invenio_handler(req)
            else:
                ret = invenio_handler(req)
            req.flush()
        except SERVER_RETURN, status:
            status = int(str(status))
            if status not in (OK, DONE):
                req.status = status
                req.headers_out['content-type'] = 'text/html'
                admin_to_be_alerted = alert_admin_for_server_status_p(
                    status, req.headers_in.get('referer'))
                if admin_to_be_alerted:
                    register_exception(req=req, alert_admin=True)
                if not req.response_sent_p:
                    start_response(req.get_wsgi_status(),
                                   req.get_low_level_headers(), sys.exc_info())
                return generate_error_page(req, admin_to_be_alerted)
            else:
                req.flush()
        except:
            register_exception(req=req, alert_admin=True)
            if not req.response_sent_p:
                req.status = HTTP_INTERNAL_SERVER_ERROR
                req.headers_out['content-type'] = 'text/html'
                start_response(req.get_wsgi_status(),
                               req.get_low_level_headers(), sys.exc_info())
                if CFG_DEVEL_SITE:
                    return [
                        "<pre>%s</pre>" % cgi.escape(
                            get_pretty_traceback(req=req,
                                                 exc_info=sys.exc_info()))
                    ]
                    from cgitb import html
                    return [html(sys.exc_info())]
                return generate_error_page(req)
            else:
                return generate_error_page(req, page_already_started=True)
コード例 #39
0
	def error_output(self, environ, start_response):
		"""WSGI mini-app to create error output

		By default, this just uses the 'error_status', 'error_headers',
		and 'error_body' attributes to generate an output page.  It can
		be overridden in a subclass to dynamically generate diagnostics,
		choose an appropriate message for the user's preferred language, etc.
		"""
		start_response('500 Internal Server Error', [('Content-Type','text/html')], sys.exc_info())
		return [cgitb.html(sys.exc_info())]
コード例 #40
0
    def render(self):
        etype, value, tb = sys.exc_info()

        if isinstance(value, openobject.errors.Concurrency):
            return self.__render(value)

        if not isinstance(value, openobject.errors.TinyException):
            return cgitb.html((etype, value, tb))

        return self.__render(value)
コード例 #41
0
ファイル: error.py プロジェクト: cwallenpoole/blog_m3
 def _displayDebugPage(self, environ, start_response):
     """
     When debugging, display an informative traceback of the exception.
     """
     import cgitb
     result = [cgitb.html(sys.exc_info())]
     start_response('200 OK', [('Content-Type', 'text/html'),
                               ('Content-Length', str(len(result[0])))],
                    sys.exc_info())
     return result
コード例 #42
0
ファイル: error_page.py プロジェクト: KDVN/KDINDO.OpenERP
 def render(self):
     etype, value, tb = sys.exc_info()
     
     if isinstance(value, common.Concurrency):
         return self.__render(value)
     
     if not isinstance(value, common.TinyException):
         return cgitb.html((etype, value, tb))
     
     return self.__render(value)
コード例 #43
0
ファイル: grid_openid.py プロジェクト: heromod/migrid
    def do_POST(self):
        """Handle all HTTP POST requests"""
        try:
            self.parsed_uri = urlparse(self.path)

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)

            self.query = {}
            for (key, val) in cgi.parse_qsl(post_data):
                # print "DEBUG: checking post input arg %s: '%s'" % (key, val)
                validate_helper = self.validators.get(key, invalid_argument)
                # Let validation errors pass to general exception handler below
                validate_helper(val)
                self.query[key] = val

            self.setUser()

            # print "DEBUG: checking path '%s'" % self.parsed_uri[2]
            valid_path(self.parsed_uri[2])
            path = self.parsed_uri[2]

            # Strip server_base before testing location
            path = path.replace("%s/" % self.server.server_base, '', 1)

            if path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/allow':
                self.handleAllow(self.query)
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
            print "ERROR: %s" % cgitb.html(sys.exc_info(), context=10)
コード例 #44
0
def whatever():
    try:
        foo = 'bar'
        baz = 1 / 0
    except Exception:
        html_output = cgitb.html(sys.exc_info())

        # Write a file so we can look at it
        open('error.html', 'w').write(html_output)
        # open a webbrowser to look at it
        webbrowser.open('file:///%s' % os.path.join(os.getcwd(), 'error.html'))
コード例 #45
0
def _tb2html(tbt, tbv, tb):
    if sys.hexversion < 0x2020000:
        from reportPackages.rlextra.utils.cgisupport import quoteValue
        import traceback
        html = quoteValue('\n'.join(
            traceback.format_tb(tb) + ['%s: %s' % (str(tbt), str(tbv))]))
    else:
        import cgitb
        html = cgitb.html((tbt, tbv, tb), context=None)
        html = html[html.find('>') + 1:html.find('<!-- The above')]
    return '<pre>%s</pre>' % html
コード例 #46
0
ファイル: test-server.py プロジェクト: AstraLuma/restracker
    def error_output(self, environ, start_response):
        """WSGI mini-app to create error output

		By default, this just uses the 'error_status', 'error_headers',
		and 'error_body' attributes to generate an output page.  It can
		be overridden in a subclass to dynamically generate diagnostics,
		choose an appropriate message for the user's preferred language, etc.
		"""
        start_response('500 Internal Server Error',
                       [('Content-Type', 'text/html')], sys.exc_info())
        return [cgitb.html(sys.exc_info())]
コード例 #47
0
ファイル: gpgopenid.py プロジェクト: f1d094/gpgopenid
    def do_GET(self):
        try:
            self.parsed_uri = urlparse(self.path)
            self.query = {}
            for k, v in cgi.parse_qsl(self.parsed_uri[4]):
                self.query[k] = v

            print self.headers

            try:
                client_ip = self.headers['X-Forwarded-For']
            except:
                self.send_error(501, 'Server error: %s' % self.path)
                print "No X-Forwarded-For header. You are NOT facing gpgopenid directly to the Internet, aren't you?"
                return

            if 'true' != self.headers['X-Auth-OpenPGP'].lower().strip():
                self.send_error(401,
                                "The http request was not signed by EnigForm")
                print "X-Auth-OpenPGP : false. The http headers were not signed by Enigform"
                return

            self.gpgkeyid = self.headers['X-Auth-OpenPGP-KeyID']

            self.setUser()

            path = self.parsed_uri[2].lower()

            if path == '/':
                self.showMainPage()
            elif path == '/openidserver':
                self.serverEndPoint(self.query)

            elif path == '/login':
                self.showLoginPage('/', '/')
            elif path == '/loginsubmit':
                self.doLogin()
            elif path.startswith('/id/'):
                self.showIdPage(path)
            elif path.startswith('/yadis/'):
                self.showYadis(path[7:])
            elif path == '/serveryadis':
                self.showServerYadis()
            else:
                self.send_response(404)
                self.end_headers()

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info(), context=10))
コード例 #48
0
ファイル: update.py プロジェクト: fangbei/pygame_sdl2
    def wrapped():
        try:
            f()
        except:
            config_dump = getattr(config, "htmlDump", "")
            config_dump = config_dump and config_dump()

            html_formatted_info = "%s<br />%s" % (cgitb.html(sys.exc_info()), config_dump)
            dump_and_open_in_browser(html_formatted_info)
            # TODO: email breakage info to maintainer
            raise
コード例 #49
0
ファイル: demo.py プロジェクト: carlodef/ipol_demo
def err_tb():
    """
    replace the default error response
    with an cgitb HTML traceback
    """
    import cgitb, sys
    tb = cgitb.html(sys.exc_info())
    def set_tb():
        """ set the traceback output """
        cherrypy.response.body = tb
        cherrypy.response.headers['Content-Length'] = None
    cherrypy.request.hooks.attach('after_error_response', set_tb)
コード例 #50
0
 def __init__(self, exc_type, exc_obj, exc_tb, title=None):
     QDialog.__init__(self)
     self.ui = Ui_ExceptHookDialog()
     self.ui.setupUi(self)
     if title:
         self.setWindowTitle(self.windowTitle() + ": " + title)
     self.ui.detailsButton.setCheckable(True)
     msg = "%s: %s" % (exc_type.__name__, exc_obj)
     self.ui.exceptionLabel.setText(msg)
     html = cgitb.html((exc_type, exc_obj, exc_tb))
     self.ui.tracebackBrowser.setText(html)
     self.resize(self.sizeHint())
コード例 #51
0
def cgi_error_handler(environ, start_response, app):
    try:
        return app(environ, start_response)

    except (KeyboardInterrupt, SystemExit):
        raise

    except Exception as e:
        headers = {'status': '500 Oops', 'content-type': 'text/html'}
        start_response(headers['status'], list(headers.items()), sys.exc_info())
        log('ERROR: %s' % repr(e), force=True)
        return [cgitb.html(sys.exc_info())]
コード例 #52
0
def whatever():
    try:
        foo = 'bar'
        baz = 1/0
    except Exception:
        html_output = cgitb.html(sys.exc_info())

        # Write a file so we can look at it
        open('error.html', 'w').write(html_output)
        # open a webbrowser to look at it
        webbrowser.open(
            'file:///%s' % os.path.join(os.getcwd(), 'error.html'))
コード例 #53
0
ファイル: update.py プロジェクト: Python3pkg/pygame_sdl2
    def wrapped():
        try:
            f()
        except:
            config_dump = getattr(config, 'htmlDump', '')
            config_dump = config_dump and config_dump()

            html_formatted_info = "%s<br />%s" % (cgitb.html(
                sys.exc_info()), config_dump)
            dump_and_open_in_browser(html_formatted_info)
            # TODO: email breakage info to maintainer
            raise
コード例 #54
0
 def send_mail_on_exception(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception, e:
         import sys, cgitb
         from pnr_utils import send_email
         send_email(
             message=u'{} \n\n {}'.format(e.message, cgitb.html(sys.exc_info())),
             subject='Py-PNR-Status Error!',
             to_addr='*****@*****.**'
         )
         raise
コード例 #55
0
ファイル: main.py プロジェクト: Jyotsnarajan/ipolDevel
def err_tb():
    """
    replace the default error response
    with an cgitb HTML traceback
    """
    import cgitb
    tb = cgitb.html(sys.exc_info())

    def set_tb():
        """ set the traceback output """
        cherrypy.response.body = tb
        cherrypy.response.headers['Content-Length'] = None

    cherrypy.request.hooks.attach('after_error_response', set_tb)
コード例 #56
0
def exception_to_text(exc_info=None):
    "Return current exception as text, or '' if no current exception."
    if exc_info is None:
        exc_info = sys.exc_info()

    if exc_info[0] is None:
        return ''  # no current exception

    if hasattr(cgitb, 'text'):
        txt = cgitb.text(exc_info)
    else:
        # eariler Pythons lack .text() ...
        # this will be ugly, but its the best I can safely do
        txt = cgitb.html(exc_info)

    return txt
コード例 #57
0
ファイル: _WSGIHandler.py プロジェクト: thangduong/kamaelia
    def _error(self, status=500, body_data=('', '', '')):
        """
        This is an internal method used to print an error to the browser and log
        it in the wsgi log.
        """
        if self.Debug:
            resource = {
                'statuscode' : status,
                'type' : 'text/html',
                'data' : cgitb.html(body_data),
            }
            self.send(resource, 'outbox')
        else:
            self.send(ErrorPages.getErrorPage(status, 'An internal error has occurred.'), 'outbox')

        self.log.write(''.join(traceback.format_exception(body_data[0], body_data[1], body_data[2], '\n')))
コード例 #58
0
    def handle_mothballer(self):
        category = self.req.get("cat")

        try:
            catdir = self.server.args["puzzles_dir"].joinpath(category)
            mb = mothballer.package(category, catdir, self.seed)
        except:
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=\"utf-8\"")
            self.end_headers()
            self.wfile.write(cgitb.html(sys.exc_info()))
            return

        self.send_response(200)
        self.send_header("Content-Type", "application/octet_stream")
        self.end_headers()
        shutil.copyfileobj(mb, self.wfile)
コード例 #59
0
ファイル: application.py プロジェクト: acorg/acmacs-whocc
async def exception_middleware(request, handler):
    try:
        return await handler(request)
    except Exception as err:
        import cgitb
        context = 10
        if "/api" in request.path:
            return web.json_response({
                "ERROR":
                str(err),
                "tb":
                cgitb.text(sys.exc_info(), context=context)
            })
        else:
            return web.Response(text=cgitb.html(sys.exc_info(),
                                                context=context),
                                content_type='text/html')
コード例 #60
0
ファイル: wuiadmin.py プロジェクト: susanych1234/virtualbox
    def _actionRegenQueuesCommon(self):
        """
        Common code for ksActionTestBoxesRegenQueues and ksActionTestCfgRegenQueues.

        Too lazy to put this in some separate place right now.
        """
        self._checkForUnknownParameters()
        ## @todo should also be changed to a POST with a confirmation dialog preceeding it.

        self._sPageTitle = 'Regenerate All Scheduling Queues'
        self._sPageBody = ''
        aoGroups = SchedGroupLogic(self._oDb).getAll()
        for oGroup in aoGroups:
            self._sPageBody += '<h3>%s (ID %#d)</h3>' % (webutils.escapeElem(
                oGroup.sName), oGroup.idSchedGroup)
            try:
                (aoErrors, asMessages) = SchedulerBase.recreateQueue(
                    self._oDb, self._oCurUser.uid, oGroup.idSchedGroup, 2)
            except Exception as oXcpt:
                self._oDb.rollback()
                self._sPageBody += '<p>SchedulerBase.recreateQueue threw an exception: %s</p>' \
                                % (webutils.escapeElem(str(oXcpt)),)
                self._sPageBody += cgitb.html(sys.exc_info())
            else:
                if len(aoErrors) == 0:
                    self._sPageBody += '<p>Successfully regenerated.</p>'
                else:
                    for oError in aoErrors:
                        if oError[1] is None:
                            self._sPageBody += '<p>%s.</p>' % (
                                webutils.escapeElem(oError[0]), )
                        ## @todo links.
                        #elif isinstance(oError[1], TestGroupData):
                        #    self._sPageBody += '<p>%s.</p>' % (webutils.escapeElem(oError[0]),);
                        #elif isinstance(oError[1], TestGroupCase):
                        #    self._sPageBody += '<p>%s.</p>' % (webutils.escapeElem(oError[0]),);
                        else:
                            self._sPageBody += '<p>%s. [Cannot link to %s]</p>' \
                                             % (webutils.escapeElem(oError[0]), webutils.escapeElem(str(oError[1])))
                for sMsg in asMessages:
                    self._sPageBody += '<p>%s<p>\n' % (
                        webutils.escapeElem(sMsg), )
        return True