예제 #1
0
def system_entry_point(wrapped, instance, args, kwargs):
    """
    Decorator for wrapping functions that enter a system context.  This should decorate every method a user might
    call.  This will allow us to add differentiation between what is a user error and what is a system failure.
    Furthermore, we will clean the exception trace so as to make more sense to the user--allowing them to know if they
    should take action themselves or pass on to the platform owners.  We will dispatch metrics and such appropriately.
    """
    try:
        _CONTEXT_STACK.append(_SYSTEM_CONTEXT)
        if _is_base_context():
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as ex:
                _reraise(ex.type, ex.value, ex.traceback)
        else:
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException:
                # Just pass-on the exception that is already wrapped and scoped
                _reraise(*_exc_info())
            except _user_exceptions.FlyteUserException:
                # Re-raise from here.
                _reraise(
                    FlyteScopedUserException,
                    FlyteScopedUserException(*_exc_info()),
                    _exc_info()[2])
            except:
                # System error, raise full stack-trace all the way up the chain.
                _reraise(
                    FlyteScopedSystemException,
                    FlyteScopedSystemException(*_exc_info(), kind=_error_model.ContainerError.Kind.RECOVERABLE),
                    _exc_info()[2])
    finally:
        _CONTEXT_STACK.pop()
예제 #2
0
    def run(self, sleep=0, mode=None, log=True, __self=None):
        if __self is not None:
            self = __self

        if not mode == "T":
            if os.name == "posix":
                signal(SIGHUP, self._signal)
            signal(SIGINT, self._signal)
            signal(SIGTERM, self._signal)

        self._running = True

        self.push(Started(self, mode))

        try:
            while self.running:
                try:
                    [f() for f in self._ticks.copy()]
                    self._flush()
                    if sleep:
                        try:
                            time.sleep(sleep)
                        except:
                            pass
                except (KeyboardInterrupt, SystemExit):
                    self._running = False
                except:
                    try:
                        if log:
                            self.push(Error(*_exc_info()))
                    finally:
                        self._flush()
        finally:
            try:
                self.push(Stopped(self))
                rtime = time.time()
                while len(self) > 0 and (time.time() - rtime) < 3:
                    try:
                        [f() for f in self._ticks.copy()]
                        self._flush()
                        if sleep:
                            time.sleep(sleep)
                        rtime = time.time()
                    except:
                        try:
                            if log:
                                self.push(Error(*_exc_info()))
                        finally:
                            self._flush()
            except:
                pass
예제 #3
0
    def run(self, sleep=0, mode=None, log=True, __self=None):
        if __self is not None:
            self = __self

        if not mode == "T":
            if os.name == "posix":
                signal(SIGHUP, self._signal)
            signal(SIGINT, self._signal)
            signal(SIGTERM, self._signal)

        self._running = True

        self.push(Started(self, mode))

        try:
            while self.running:
                try:
                    [f() for f in self._ticks.copy()]
                    self._flush()
                    if sleep:
                        try:
                            time.sleep(sleep)
                        except:
                            pass
                except (KeyboardInterrupt, SystemExit):
                    self._running = False
                except:
                    try:
                        if log:
                            self.push(Error(*_exc_info()))
                    finally:
                        self._flush()
        finally:
            try:
                self.push(Stopped(self))
                rtime = time.time()
                while len(self) > 0 and (time.time() - rtime) < 3:
                    try:
                        [f() for f in self._ticks.copy()]
                        self._flush()
                        if sleep:
                            time.sleep(sleep)
                    except:
                        try:
                            if log:
                                self.push(Error(*_exc_info()))
                        finally:
                            self._flush()
            except:
                pass
예제 #4
0
def get_error_page(status, **kwargs):
    """Return an HTML page, containing a pretty error response.

    status should be an int or a str.
    kwargs will be interpolated into the page template.
    """
    import cherrypy

    try:
        code, reason, message = _httputil.valid_status(status)
    except ValueError:
        raise cherrypy.HTTPError(500, _exc_info()[1].args[0])

    # We can't use setdefault here, because some
    # callers send None for kwarg values.
    if kwargs.get('status') is None:
        kwargs['status'] = "%s %s" % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__

    for k, v in iteritems(kwargs):
        if v is None:
            kwargs[k] = ""
        else:
            kwargs[k] = _escape(kwargs[k])

    # Use a custom template or callable for the error page?
    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                return error_page(**kwargs)
            else:
                data = open(error_page, 'rb').read()
                return tonative(data) % kwargs
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += "<br />"
            m += "In addition, the custom error page failed:\n<br />%s" % e
            kwargs['message'] = m

    return _HTTPErrorTemplate % kwargs
예제 #5
0
 def _start(self):
     # TODO: Maybe this should just be Greenlet.spawn()?
     try:
         greenlet = self.greenlet_class(self.handle)
         greenlet.switch()
     except:  # pylint:disable=bare-except
         self.hub.handle_error(None, *sys._exc_info())  # pylint:disable=no-member
예제 #6
0
    def _send(self, event, channel, errors=False, log=True):
        eargs = event.args
        ekwargs = event.kwargs

        r = False
        for handler in self._getHandlers(channel):
            try:
                #stime = time.time()
                if handler._passEvent:
                    r = handler(event, *eargs, **ekwargs)
                else:
                    r = handler(*eargs, **ekwargs)
                #etime = time.time()
                #ttime = (etime - stime) * 1e3
                #print "%s: %0.02f ms" % (reprhandler(handler), ttime)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                if log:
                    etype, evalue, etraceback = _exc_info()
                    self.push(Error(etype, evalue, etraceback, handler=handler))
                if errors:
                    raise
                else:
                    _exc_clear()
            if r is not None and r and handler.filter:
                return r
        return r
예제 #7
0
def unexpected_json_error_handler():
    """request.error_response"""

    (typ, value, tb) = _exc_info()
    if typ:
        debug = False
        if hasattr(cherrypy.request, 'params'):
            params = cherrypy.request.params
            debug = 'debug' in params and params['debug']

        response = cherrypy.response
        response.headers['Content-Type'] = 'application/json'
        response.headers.pop('Content-Length', None)
        content = {}
        if isinstance(value, ExtendedHTTPError):
            content.update({'errors': value.errors})
        if isinstance(typ, cherrypy.HTTPError):
            cherrypy._cperror.clean_headers(value.code)
            response.status = value.status
            content.update({'code': value.code, 'reason': value.reason,
                            'message': value._message})
        elif isinstance(typ, (TypeError, ValueError, KeyError)):
            cherrypy._cperror.clean_headers(400)
            response.status = 400
            reason, default_message = _httputil.response_codes[400]
            content = {'code': 400, 'reason': reason,
                       'message': value.message or default_message}

        if cherrypy.serving.request.show_tracebacks or debug:
            tb = _format_exc()
            content['traceback'] = tb
        response.body = json.dumps(content).encode('utf-8')
예제 #8
0
def format_exc(exc = None):
    if exc is None:
        exc = _exc_info()
    if exc == (None, None, None):
        return ''
    import traceback
    return ''.join(traceback.format_exception(*exc))
예제 #9
0
def with_(manager, action):
    """Execute an action within the scope of a context manager.

    Arguments:
        manager: The context manager instance to use.
        action: The callable to execute. Must accept the `as` value
            of the context manager as the only positional argument.

    Returns:
        Any: Return value of the executed action.
        None: If the manager suppresses an exception from the action.

    Raises:
        Any: If raised by calling the action and not suppressed by the
            manager, or if raised by the manager, or if the manager
            does not implement the context manager protocol correctly.
    """
    exit_ = type(manager).__exit__
    value = type(manager).__enter__(manager)
    try:
        result = action(value)
    except:
        if not exit_(manager, *_exc_info()):
            raise
        return None
    exit_(manager, None, None, None)
    return result
예제 #10
0
파일: _cperror.py 프로젝트: R4M80MrX/eve-1
def format_exc(exc=None):
    if exc is None:
        exc = _exc_info()
    if exc == (None, None, None):
        return ''
    import traceback
    return ''.join(traceback.format_exception(*exc))
def format_exc(exc=None):
    """Return exc (or sys.exc_info if None), formatted."""
    if exc is None:
        exc = _exc_info()
    if exc == (None, None, None):
        return ""
    import traceback
    return "".join(traceback.format_exception(*exc))
예제 #12
0
 def tick(self):
     if self._ticks:
         try:
             [f() for f in self._ticks.copy()]
         except:
             etype, evalue, etraceback = _exc_info()
             self.fire(Error(etype, evalue, format_tb(etraceback)))
     if self:
         self._flush()
예제 #13
0
 def tick(self):
     if self._ticks:
         try:
             [f() for f in self._ticks.copy()]
         except:
             etype, evalue, etraceback = _exc_info()
             self.fire(Error(etype, evalue, format_tb(etraceback)))
     if self:
         self._flush()
예제 #14
0
    def _dispatcher(self, event):

        if event.cancelled:
            return

        if event.complete:
            if not getattr(event, "cause", None):
                event.cause = event
            event.effects = 1  # event itself counts (must be done)
        eargs = event.args
        ekwargs = event.kwargs

        if self._cache_needs_refresh:
            # Don't call self._cache.clear() from other threads,
            # this may interfere with cache rebuild.
            self._cache.clear()
            self._cache_needs_refresh = False
        try:  # try/except is fastest if successful in most cases
            event_handlers = self._cache[event.name]
        except KeyError:
            h = self.get_handlers(event)

            # todo refactor priority sort method

            # sorted events by priority
            event_handlers = sorted(h, key=lambda x: x.priority, reverse=True)

            self._cache[event.name] = event_handlers

        self._currently_handling = event

        result = None

        for event_handler in event_handlers:
            event.handler = event_handler
            # todo refactor arguments number
            try:
                if event_handler.event:
                    result = event_handler(event, *eargs, **ekwargs)
                else:
                    result = event_handler(*eargs, **ekwargs)
            except KeyboardInterrupt:
                self.stop()
            except SystemExit as e:
                self.stop(e.code)
            except:
                result = _exc_info()

                # todo raise a failure exception

            if result is not None:
                event.result = result

            if event.stopped:
                break  # Stop further event processing

        self._currently_handling = None
예제 #15
0
파일: scopes.py 프로젝트: flyteorg/flytekit
def system_entry_point(wrapped, instance, args, kwargs):
    """
    The reason these two (see the user one below) decorators exist is to categorize non-Flyte exceptions at arbitrary
    locations. For example, while there is a separate ecosystem of Flyte-defined user and system exceptions
    (see the FlyteException hierarchy), and we can easily understand and categorize those, if flytekit comes upon
    a random ``ValueError`` or other non-flytekit defined error, how would we know if it was a bug in flytekit versus an
    error with user code or something the user called? The purpose of these decorators is to categorize those (see
    the last case in the nested try/catch below.

    Decorator for wrapping functions that enter a system context. This should decorate every method that may invoke some
    user code later on down the line. This will allow us to add differentiation between what is a user error and
    what is a system failure. Furthermore, we will clean the exception trace so as to make more sense to the
    user -- allowing them to know if they should take action themselves or pass on to the platform owners.
    We will dispatch metrics and such appropriately.
    """
    try:
        _CONTEXT_STACK.append(_SYSTEM_CONTEXT)
        if _is_base_context():
            # If this is the first time either of this decorator, or the one below is called, then we unwrap the
            # exception. The first time these decorators are used is currently in the entrypoint.py file. The scoped
            # exceptions are unwrapped because at that point, we want to return the underlying error to the user.
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as ex:
                raise ex.value
        else:
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as scoped:
                raise scoped
            except _user_exceptions.FlyteUserException:
                # Re-raise from here.
                raise FlyteScopedUserException(*_exc_info())
            except Exception:
                # This is why this function exists - arbitrary exceptions that we don't know what to do with are
                # interpreted as system errors.
                # System error, raise full stack-trace all the way up the chain.
                raise FlyteScopedSystemException(
                    *_exc_info(),
                    kind=_error_model.ContainerError.Kind.RECOVERABLE)
    finally:
        _CONTEXT_STACK.pop()
예제 #16
0
def format_exc(exc=None):
    """Return exc (or sys.exc_info if None), formatted."""
    try:
        if exc is None:
            exc = _exc_info()
        if exc == (None, None, None):
            return ''
        import traceback
        return ''.join(traceback.format_exception(*exc))
    finally:
        del exc
예제 #17
0
파일: wsgi.py 프로젝트: xmonader/circuits
    def _on_request(self, event, req, res):
        if not self.apps:
            return

        parts = req.path.split("/")

        candidates = []
        for i in range(len(parts)):
            k = "/".join(parts[:(i + 1)]) or "/"
            if k in self.apps:
                candidates.append((k, self.apps[k]))
        candidates = sorted(candidates, key=itemgetter(0), reverse=True)

        if not candidates:
            return

        path, app = candidates[0]

        buffer = StringIO()

        def start_response(status, headers, exc_info=None):
            res.status = int(status.split(" ", 1)[0])
            for header in headers:
                res.headers.add_header(*header)
            return buffer.write

        errors = self.errors[path]

        environ = create_environ(errors, path, req)

        try:
            body = app(environ, start_response)
            if isinstance(body, list):
                _body = type(body[0])() if body else ""
                body = _body.join(body)
            elif isinstance(body, GeneratorType):
                res.body = body
                res.stream = True
                return res

            if not body:
                if not buffer.tell():
                    return empty
                else:
                    buffer.seek(0)
                    return buffer
            else:
                return body
        except Exception as error:
            etype, evalue, etraceback = _exc_info()
            error = (etype, evalue, format_tb(etraceback))
            return httperror(req, res, 500, error=error)
        finally:
            event.stop()
예제 #18
0
파일: wsgi.py 프로젝트: spaceone/circuits
    def _on_request(self, event, req, res):
        if not self.apps:
            return

        parts = req.path.split("/")

        candidates = []
        for i in range(len(parts)):
            k = "/".join(parts[:(i + 1)]) or "/"
            if k in self.apps:
                candidates.append((k, self.apps[k]))
        candidates = sorted(candidates, key=itemgetter(0), reverse=True)

        if not candidates:
            return

        path, app = candidates[0]

        buffer = StringIO()

        def start_response(status, headers, exc_info=None):
            res.status = int(status.split(" ", 1)[0])
            for header in headers:
                res.headers.add_header(*header)
            return buffer.write

        errors = self.errors[path]

        environ = create_environ(errors, path, req)

        try:
            body = app(environ, start_response)
            if isinstance(body, list):
                _body = type(body[0])() if body else ""
                body = _body.join(body)
            elif isinstance(body, GeneratorType):
                res.body = body
                res.stream = True
                return res

            if not body:
                if not buffer.tell():
                    return empty
                else:
                    buffer.seek(0)
                    return buffer
            else:
                return body
        except Exception as error:
            etype, evalue, etraceback = _exc_info()
            error = (etype, evalue, format_tb(etraceback))
            return httperror(req, res, 500, error=error)
        finally:
            event.stop()
예제 #19
0
파일: _cperror.py 프로젝트: coady/cherrypy
def format_exc(exc=None):
    """Return exc (or sys.exc_info if None), formatted."""
    try:
        if exc is None:
            exc = _exc_info()
        if exc == (None, None, None):
            return ''
        import traceback
        return ''.join(traceback.format_exception(*exc))
    finally:
        del exc
예제 #20
0
    def _on_request(self, event, request, response):
        if self.path and not request.path.startswith(self.path):
            return

        req = event
        path = request.path

        if self.path is not None:
            path = path[len(self.path):]
            req.path = path

        self._request = request
        self._response = response

        try:
            return self.app(self.createEnviron(), self.start_response)
        except Exception, error:
            status = 500
            message = str(error)
            error = _exc_info()
            etype, evalue, etraceback = _exc_info()
            error = (etype, evalue, format_tb(etraceback))
            return HTTPError(request, response, status, message, error)
예제 #21
0
def get_traceback_string():
    """
    Returns the traceback unicode string for the last error
    """

    from sys import exc_info as _exc_info
    exc = _exc_info()
    if exc == (None, None, None):
        return ""
    import traceback
    tb = "".join(traceback.format_exception(*exc))

    # Fertig
    return unicode(tb, errors="replace")
예제 #22
0
def get_traceback_string():
    """
    Gibt den Traceback-String des letzten Fehlers zurück
    """

    from sys import exc_info as _exc_info
    exc = _exc_info()
    if exc == (None, None, None):
        return ""
    import traceback
    tb = "".join(traceback.format_exception(*exc))

    # Fertig
    return tb
예제 #23
0
def get_traceback_string():
    """
    Gibt den Traceback-String des letzten Fehlers zurück
    """

    from sys import exc_info as _exc_info
    exc = _exc_info()
    if exc == (None, None, None):
        return ""
    import traceback
    tb = "".join(traceback.format_exception(*exc))

    # Fertig
    return tb
예제 #24
0
파일: wsgi.py 프로젝트: A-K/naali
    def _on_request(self, event, request, response):
        if self.path and not request.path.startswith(self.path):
            return

        req = event
        path = request.path

        if self.path is not None:
            path = path[len(self.path):]
            req.path = path

        self._request = request
        self._response = response

        try:
            return self.app(self.createEnviron(), self.start_response)
        except Exception, error:
            status = 500
            message = str(error)
            error = _exc_info()
            etype, evalue, etraceback = _exc_info()
            error = (etype, evalue, format_tb(etraceback))
            return HTTPError(request, response, status, message, error)
예제 #25
0
def get_traceback_string():
    """
    Returns the traceback unicode string for the last error
    """

    from sys import exc_info as _exc_info
    exc = _exc_info()
    if exc == (None, None, None):
        return ""
    import traceback
    tb = "".join(traceback.format_exception(*exc))

    # Fertig
    return unicode(tb, errors = "replace")
예제 #26
0
    def __init__(self, status=500, message=None):
        self.status = status
        try:
            self.code, self.reason, defaultmsg = _httputil.valid_status(status)
        except ValueError:
            raise self.__class__(500, _exc_info()[1].args[0])

        if self.code < 400 or self.code > 599:
            raise ValueError('status must be between 400 and 599.')

        # See http://www.python.org/dev/peps/pep-0352/
        # self.message = message
        self._message = message or defaultmsg
        CherryPyException.__init__(self, status, message)
예제 #27
0
파일: _cperror.py 프로젝트: ducin/cherrypy
    def __init__(self, status=500, message=None):
        self.status = status
        try:
            self.code, self.reason, defaultmsg = _httputil.valid_status(status)
        except ValueError:
            raise self.__class__(500, _exc_info()[1].args[0])

        if self.code < 400 or self.code > 599:
            raise ValueError("status must be between 400 and 599.")

        # See http://www.python.org/dev/peps/pep-0352/
        # self.message = message
        self._message = message or defaultmsg
        CherryPyException.__init__(self, status, message)
예제 #28
0
파일: scopes.py 프로젝트: flyteorg/flytekit
def user_entry_point(wrapped, instance, args, kwargs):
    """
    See the comment for the system_entry_point above as well.

    Decorator for wrapping functions that enter into a user context.  This will help us differentiate user-created
    failures even when it is re-entrant into system code.

    Note: a user_entry_point can ONLY ever be called from within a @system_entry_point wrapped function, therefore,
    we can always ensure we will hit a system_entry_point to correctly reformat our exceptions.  Also, any exception
    we create here will only be handled within our system code so we don't need to worry about leaking weird exceptions
    to the user.
    """
    try:
        _CONTEXT_STACK.append(_USER_CONTEXT)
        if _is_base_context():
            # See comment at this location for system_entry_point
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as ex:
                raise ex.value
        else:
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as scoped:
                raise scoped
            except _user_exceptions.FlyteUserException:
                raise FlyteScopedUserException(*_exc_info())
            except _system_exceptions.FlyteSystemException:
                raise FlyteScopedSystemException(*_exc_info())
            except Exception:
                # This is why this function exists - arbitrary exceptions that we don't know what to do with are
                # interpreted as user exceptions.
                # This will also catch FlyteUserException re-raised by the system_entry_point handler
                raise FlyteScopedUserException(*_exc_info())
    finally:
        _CONTEXT_STACK.pop()
예제 #29
0
def handle_os_exceptions():
    """
    Handles airfs exceptions and raise standard OS exceptions.
    """
    try:
        yield

    except AirfsInternalException as exception:
        exc_type, exc_value, _ = _exc_info()
        raise _OS_EXCEPTIONS.get(
            exc_type,
            OSError)(exc_value) from (exception if _FULLTRACEBACK else None)

    except Exception:
        raise
예제 #30
0
    def run(self, sleep=0, mode=None, errors=False, log=True, __self=None):
        if __self is not None:
            self = __self

        if not mode == "T":
            #signal(SIGHUP, self._signal)
            signal(SIGINT, self._signal)
            signal(SIGTERM, self._signal)

        self._running = True

        self.push(Started(self, mode), "started")

        try:
            while self._running:
                try:
                    [f() for f in self.ticks.copy()]
                    self.flush()
                    if sleep:
                        try:
                            time.sleep(sleep)
                        except:
                            pass
                except (KeyboardInterrupt, SystemExit):
                    self._running = False
                except:
                    try:
                        if log:
                            self.push(Error(*_exc_info()), "error")
                        if errors:
                            raise
                        else:
                            _exc_clear()
                    except:
                        pass
        finally:
            try:
                self.push(Stopped(self), "stopped")
                rtime = time.time()
                while len(self) > 0 and (time.time() - rtime) < 3:
                    [f() for f in self.ticks.copy()]
                    self.flush()
                    if sleep:
                        time.sleep(sleep)
                    rtime = time.time()
            except:
                pass
예제 #31
0
파일: main.py 프로젝트: codeguycool/CEC
def handle_error():
    """
    Note:
        Not catch Httpd code 3XX~4XX exception. These exception will just response to client. 
    """
    excpetion_inst = _exc_info()[1]

    if isinstance(excpetion_inst, RequestError):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        cherrypy.response.status = excpetion_inst.http_status
        resp = Response(success=False, err_code=excpetion_inst.code, err_msg=excpetion_inst.get_msg())
        cherrypy.response.body = json.dumps(resp)
    else:  # hide exception information
        cherrypy.response.show_tracebacks = False
        cherrypy.response.status = 500
        cherrypy.response.body = [
            "<html><body>%s</body></html>" % ERR_MSG[500]
        ]
예제 #32
0
    def _send(self, event, channel, errors=False, log=True):
        eargs = event.args
        ekwargs = event.kwargs

        if event.start is not None:
            self.push(Start(event), *event.start)

        retval = None
        handler = None

        for handler in self._getHandlers(channel):
            event.handler = handler
            if event.before is not None:
                self.push(Before(event, handler), *event.before)
            try:
                if handler._passEvent:
                    retval = handler(event, *eargs, **ekwargs)
                else:
                    retval = handler(*eargs, **ekwargs)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                etype, evalue, etraceback = _exc_info()
                if event.failure is not None:
                    error = (etype, evalue, etraceback)
                    self.push(Failure(event, handler, error), *event.failure)
                if log:
                    self.push(Error(etype, evalue, etraceback,
                                    handler=handler))
                if errors:
                    raise

            if retval is not None and retval and handler.filter:
                if event.filter is not None:
                    self.push(Filter(event, handler, retval), *event.filter)
                return retval

            if event.success is not None:
                self.push(Success(event, handler, retval), *event.success)

        if event.end is not None:
            self.push(End(event, handler, retval), *event.end)

        return retval
예제 #33
0
파일: __init__.py 프로젝트: Belsepubi/naali
    def _send(self, event, channel, errors=False, log=True):
        eargs = event.args
        ekwargs = event.kwargs

        if event.start is not None:
            self.push(Start(event), *event.start)

        retval = None
        handler = None

        for handler in self._getHandlers(channel):
            event.handler = handler
            if event.before is not None:
                self.push(Before(event, handler), *event.before)
            try:
                if handler._passEvent:
                    retval = handler(event, *eargs, **ekwargs)
                else:
                    retval = handler(*eargs, **ekwargs)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                etype, evalue, etraceback = _exc_info()
                if event.failure is not None:
                    error = (etype, evalue, etraceback)
                    self.push(Failure(event, handler, error), *event.failure)
                if log:
                    self.push(Error(etype, evalue, etraceback, handler=handler))
                if errors:
                    raise

            if retval is not None and retval and handler.filter:
                if event.filter is not None:
                    self.push(Filter(event, handler, retval), *event.filter)
                return retval

            if event.success is not None:
                self.push(Success(event, handler, retval), *event.success)

        if event.end is not None:
            self.push(End(event, handler, retval), *event.end)

        return retval
예제 #34
0
파일: scopes.py 프로젝트: ybubnov/flytekit
def user_entry_point(wrapped, instance, args, kwargs):
    """
    Decorator for wrapping functions that enter into a user context.  This will help us differentiate user-created
    failures even when it is re-entrant into system code.

    Note: a user_entry_point can ONLY ever be called from within a @system_entry_point wrapped function, therefore,
    we can always ensure we will hit a system_entry_point to correctly reformat our exceptions.  Also, any exception
    we create here will only be handled within our system code so we don't need to worry about leaking weird exceptions
    to the user.
    """
    try:
        _CONTEXT_STACK.append(_USER_CONTEXT)
        if _is_base_context():
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException as ex:
                _reraise(ex.type, ex.value, ex.traceback)
        else:
            try:
                return wrapped(*args, **kwargs)
            except FlyteScopedException:
                # Just pass on the already wrapped and scoped exception
                _reraise(*_exc_info())
            except _user_exceptions.FlyteUserException:
                _reraise(
                    FlyteScopedUserException,
                    FlyteScopedUserException(*_exc_info()),
                    _exc_info()[2],
                )
            except _system_exceptions.FlyteSystemException:
                _reraise(
                    FlyteScopedSystemException,
                    FlyteScopedSystemException(*_exc_info()),
                    _exc_info()[2],
                )
            except Exception:
                # Any non-platform raised exception is a user exception.
                # This will also catch FlyteUserException re-raised by the system_entry_point handler
                _reraise(
                    FlyteScopedUserException,
                    FlyteScopedUserException(*_exc_info()),
                    _exc_info()[2],
                )
    finally:
        _CONTEXT_STACK.pop()
예제 #35
0
def get_error_page(status, **kwargs):
    """Return an HTML page, containing a pretty error response.
    
    status should be an int or a str.
    kwargs will be interpolated into the page template.
    """
    import cherrypy
    try:
        code, reason, message = _httputil.valid_status(status)
    except ValueError as x:
        raise cherrypy.HTTPError(500, x.args[0])

    if kwargs.get('status') is None:
        kwargs['status'] = '%s %s' % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__
    for k, v in iteritems(kwargs):
        if v is None:
            kwargs[k] = ''
        else:
            kwargs[k] = _escape(kwargs[k])

    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                return error_page(**kwargs)
            return open(error_page, 'rb').read() % kwargs
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += '<br />'
            m += 'In addition, the custom error page failed:\n<br />%s' % e
            kwargs['message'] = m

    return _HTTPErrorTemplate % kwargs
예제 #36
0
파일: main.py 프로젝트: codeguycool/CEC
def handle_error():
    """
    Note:
        Not catch Httpd code 3XX~4XX exception. These exception will just response to client. 
    """
    excpetion_inst = _exc_info()[1]

    if isinstance(excpetion_inst, RequestError):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        cherrypy.response.status = excpetion_inst.http_status
        resp = Response(success=False,
                        err_code=excpetion_inst.code,
                        err_msg=excpetion_inst.get_msg())
        cherrypy.response.body = json.dumps(resp)
    else:  # hide exception information
        cherrypy.response.show_tracebacks = False
        cherrypy.response.status = 500
        cherrypy.response.body = [
            "<html><body>%s</body></html>" % ERR_MSG[500]
        ]
예제 #37
0
파일: wsgi.py 프로젝트: Belsepubi/naali
    def request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        req = event
        path = request.path

        if self.path is not None:
            path = path[len(self.path):]
            req.path = path

        self._request = request
        self._response = response

        try:
            return "".join(self.app(self._createEnviron(), self.start_response))
        except Exception, error:
            status = error.code
            message = error.message
            error = _exc_info()
            return HTTPError(request, response, status, message, error)
예제 #38
0
    def request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        req = event
        path = request.path

        if self.path is not None:
            path = path[len(self.path):]
            req.path = path

        self._request = request
        self._response = response

        try:
            return "".join(self.app(self._createEnviron(),
                                    self.start_response))
        except Exception, error:
            status = error.code
            message = error.message
            error = _exc_info()
            return HTTPError(request, response, status, message, error)
예제 #39
0
def unexpected_json_error_handler():
    """request.error_response"""

    (typ, value, tb) = _exc_info()
    if typ:
        debug = False
        if hasattr(cherrypy.request, 'params'):
            params = cherrypy.request.params
            debug = 'debug' in params and params['debug']

        response = cherrypy.response
        response.headers['Content-Type'] = 'application/json'
        response.headers.pop('Content-Length', None)
        content = {}
        if isinstance(value, ExtendedHTTPError):
            content.update({'errors': value.errors})
        if isinstance(typ, cherrypy.HTTPError):
            cherrypy._cperror.clean_headers(value.code)
            response.status = value.status
            content.update({
                'code': value.code,
                'reason': value.reason,
                'message': value._message
            })
        elif isinstance(typ, (TypeError, ValueError, KeyError)):
            cherrypy._cperror.clean_headers(400)
            response.status = 400
            reason, default_message = _httputil.response_codes[400]
            content = {
                'code': 400,
                'reason': reason,
                'message': value.message or default_message
            }

        if cherrypy.serving.request.show_tracebacks or debug:
            tb = _format_exc()
            content['traceback'] = tb
        response.body = json.dumps(content).encode('utf-8')
예제 #40
0
    def __handleEvent(self, event, channel):
        eargs = event.args
        ekwargs = event.kwargs

        retval = None
        handler = None

        for handler in self._getHandlers(channel):
            attrs = self._handlerattrs[handler]
            event.handler = handler
            try:
                if attrs["event"]:
                    retval = handler(event, *eargs, **ekwargs)
                else:
                    retval = handler(*eargs, **ekwargs)
                event.value.value = retval
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                etype, evalue, etraceback = _exc_info()
                event.value.errors = True
                event.value.value = etype, evalue, format_tb(etraceback)
                self.fire(Error(etype, evalue, format_tb(etraceback), handler))
                if event.failure is not None:
                    error = (etype, evalue, format_tb(etraceback))
                    self.fire(Failure(event, handler, error), *event.failure)

            if retval is not None:
                if retval and attrs["filter"]:
                    if event.filter is not None:
                        self.fire(Filter(event, handler, retval),
                                  *event.filter)
                    return  # Filter
                if event.success is not None:
                    self.fire(Success(event, handler, retval), *event.success)

        if event.end is not None:
            self.fire(End(event, handler, retval), *event.end)
예제 #41
0
def get_error_page(status, **kwargs):
    import cherrypy
    try:
        code, reason, message = _httputil.valid_status(status)
    except ValueError as x:
        raise cherrypy.HTTPError(500, x.args[0])

    if kwargs.get('status') is None:
        kwargs['status'] = '%s %s' % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__
    for k, v in iteritems(kwargs):
        if v is None:
            kwargs[k] = ''
        else:
            kwargs[k] = _escape(kwargs[k])

    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                return error_page(**kwargs)
            return open(error_page, 'rb').read() % kwargs
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += '<br />'
            m += 'In addition, the custom error page failed:\n<br />%s' % e
            kwargs['message'] = m

    return _HTTPErrorTemplate % kwargs
예제 #42
0
    def __handleEvent(self, event, channel):
        eargs = event.args
        ekwargs = event.kwargs

        retval = None
        handler = None

        for handler in self._getHandlers(channel):
            attrs = self._handlerattrs[handler]
            event.handler = handler
            try:
                if attrs["event"]:
                    retval = handler(event, *eargs, **ekwargs)
                else:
                    retval = handler(*eargs, **ekwargs)
                event.value.value = retval
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                etype, evalue, etraceback = _exc_info()
                event.value.errors = True
                event.value.value = etype, evalue, format_tb(etraceback)
                self.fire(Error(etype, evalue, format_tb(etraceback), handler))
                if event.failure is not None:
                    error = (etype, evalue, format_tb(etraceback))
                    self.fire(Failure(event, handler, error), *event.failure)

            if retval is not None:
                if retval and attrs["filter"]:
                    if event.filter is not None:
                        self.fire(Filter(event, handler, retval), *event.filter)
                    return  # Filter
                if event.success is not None:
                    self.fire(Success(event, handler, retval), *event.success)

        if event.end is not None:
            self.fire(End(event, handler, retval), *event.end)
    def render(__stream, econtext, rcontext, __i18n_domain=None, __i18n_context=None):
        __append = __stream.append
        __re_amp = g_re_amp
        __token = None
        __re_needs_escape = g_re_needs_escape

        def __convert(target):
            if (target is None):
                return
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except AttributeError:
                            __converted = convert(target)
                            target = (str(target) if (target is __converted) else __converted)
                        else:
                            target = target()
            return target

        def __quote(target, quote, quote_entity, default, default_marker):
            if (target is None):
                return
            if (target is default_marker):
                return default
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except:
                            __converted = convert(target)
                            target = (str(target) if (target is __converted) else __converted)
                        else:
                            return target()
                if (target is not None):
                    try:
                        escape = (__re_needs_escape(target) is not None)
                    except TypeError:
                        pass
                    else:
                        if escape:
                            if ('&' in target):
                                target = target.replace('&', '&amp;')
                            if ('<' in target):
                                target = target.replace('<', '&lt;')
                            if ('>' in target):
                                target = target.replace('>', '&gt;')
                            if ((quote is not None) and (quote in target)):
                                target = target.replace(quote, quote_entity)
            return target
        translate = econtext['__translate']
        decode = econtext['__decode']
        convert = econtext['__convert']
        on_error_handler = econtext['__on_error_handler']
        try:
            getitem = econtext.__getitem__
            get = econtext.get
            __append('\n\n')
            __backup_perm_storage_140183229935688 = get('perm_storage', __marker)

            # <Value 'industry.perm_storage' (3:32)> -> __value
            __token = 106
            __value = _lookup_attr(getitem('industry'), 'perm_storage')
            econtext['perm_storage'] = __value
            __append('\n    ')
            __append('\n\n    ')

            # <Interpolation value=<Substitution '\n    switch(FEAT_INDUSTRIES, SELF, ${industry.id}_secondary_increase_closure_counter,\n           STORE_PERM((1 + LOAD_PERM(${perm_storage.closure_counter})), ${perm_storage.closure_counter})) {\n        return 0;\n    }\n    switch(FEAT_INDUSTRIES, SELF, ${industry.id}_secondary_reset_closure_counter, [STORE_PERM(0, ${perm_storage.closure_counter}), 1]) {\n        return 0;\n    }\n    ' (6:111)> braces_required=True translation=False at 7f7ef3b4a2b0> -> __content_140183249773656
            __token = 330
            __token = 362
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __token = 450
            __content_140183249773656_448 = _lookup_attr(getitem('perm_storage'), 'closure_counter')
            __content_140183249773656_448 = __quote(__content_140183249773656_448, '\x00', '&#0;', None, False)
            __token = 485
            __content_140183249773656_483 = _lookup_attr(getitem('perm_storage'), 'closure_counter')
            __content_140183249773656_483 = __quote(__content_140183249773656_483, '\x00', '&#0;', None, False)
            __token = 579
            __content_140183249773656_577 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656_577 = __quote(__content_140183249773656_577, '\x00', '&#0;', None, False)
            __token = 642
            __content_140183249773656_640 = _lookup_attr(getitem('perm_storage'), 'closure_counter')
            __content_140183249773656_640 = __quote(__content_140183249773656_640, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s%s%s%s%s%s%s%s%s' % ('\n    switch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_secondary_increase_closure_counter,\n           STORE_PERM((1 + LOAD_PERM(', (__content_140183249773656_448 if (__content_140183249773656_448 is not None) else ''), ')), ', (__content_140183249773656_483 if (__content_140183249773656_483 is not None) else ''), ')) {\n        return 0;\n    }\n    switch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656_577 if (__content_140183249773656_577 is not None) else ''), '_secondary_reset_closure_counter, [STORE_PERM(0, ', (__content_140183249773656_640 if (__content_140183249773656_640 is not None) else ''), '), 1]) {\n        return 0;\n    }\n    ', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)

            # <Interpolation value=<Substitution '\n    switch(FEAT_INDUSTRIES, SELF, ${industry.id}_check_secondary_production_level, [\n                transported_last_month_1 > 0 ||\n                transported_last_month_2 > 0 ||\n                (current_date - LOAD_PERM(${perm_storage.date_received_1})) ' (14:128)> braces_required=True translation=False at 7f7ef3b4afd0> -> __content_140183249773656
            __token = 837
            __token = 869
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __token = 1058
            __content_140183249773656_1056 = _lookup_attr(getitem('perm_storage'), 'date_received_1')
            __content_140183249773656_1056 = __quote(__content_140183249773656_1056, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s%s%s' % ('\n    switch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_check_secondary_production_level, [\n                transported_last_month_1 > 0 ||\n                transported_last_month_2 > 0 ||\n                (current_date - LOAD_PERM(', (__content_140183249773656_1056 if (__content_140183249773656_1056 is not None) else ''), ')) ', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)
            __append('<')

            # <Interpolation value=<Substitution ' 30 ||\n                (current_date - LOAD_PERM(${perm_storage.date_received_2})) ' (18:77)> braces_required=True translation=False at 7f7ef3b4a940> -> __content_140183249773656
            __token = 1092
            __token = 1142
            __content_140183249773656 = _lookup_attr(getitem('perm_storage'), 'date_received_2')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s' % (' 30 ||\n                (current_date - LOAD_PERM(', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), ')) ', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)
            __append('<')

            # <Interpolation value=<Substitution ' 30 ||\n                (current_date - LOAD_PERM(${perm_storage.date_received_3})) ' (19:77)> braces_required=True translation=False at 7f7ef3b4a710> -> __content_140183249773656
            __token = 1176
            __token = 1226
            __content_140183249773656 = _lookup_attr(getitem('perm_storage'), 'date_received_3')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s' % (' 30 ||\n                (current_date - LOAD_PERM(', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), ')) ', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)
            __append('<')

            # <Interpolation value=<Substitution ' 30\n                ]\n            ) {\n        0: ${industry.id}_secondary_increase_closure_counter;\n        ${industry.id}_secondary_reset_closure_counter;\n    }\n' (20:77)> braces_required=True translation=False at 7f7ef3b4a7b8> -> __content_140183249773656
            __token = 1260
            __token = 1310
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __token = 1369
            __content_140183249773656_1367 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656_1367 = __quote(__content_140183249773656_1367, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s%s%s' % (' 30\n                ]\n            ) {\n        0: ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_secondary_increase_closure_counter;\n        ', (__content_140183249773656_1367 if (__content_140183249773656_1367 is not None) else ''), '_secondary_reset_closure_counter;\n    }\n', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)
            if (__backup_perm_storage_140183229935688 is __marker):
                del econtext['perm_storage']
            else:
                econtext['perm_storage'] = __backup_perm_storage_140183229935688
            __append('\n\n\n')
            __append('\n\n')

            # <Interpolation value=<Substitution '\nswitch(FEAT_INDUSTRIES, SELF, ${industry.id}_secondary_close_random, (extra_callback_info2 & 32)) {\n\t0: return CB_RESULT_IND_PROD_CLOSE;\n\treturn CB_RESULT_IND_PROD_NO_CHANGE;\n}\n\n' (31:96)> braces_required=True translation=False at 7f7ef3b4a6d8> -> __content_140183249773656
            __token = 1623
            __token = 1655
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s' % ('\nswitch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_secondary_close_random, (extra_callback_info2 & 32)) {\n\t0: return CB_RESULT_IND_PROD_CLOSE;\n\treturn CB_RESULT_IND_PROD_NO_CHANGE;\n}\n\n', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)

            # <Interpolation value=<Substitution '\nswitch(FEAT_INDUSTRIES, SELF, ${industry.id}_secondary_had_produced_check, LOAD_PERM(${industry.perm_storage.closure_counter})) {\n\t0..60: return CB_RESULT_IND_PROD_NO_CHANGE;\n\t${industry.id}_secondary_close_random;\n}\n\n' (37:57)> braces_required=True translation=False at 7f7ef3a790f0> -> __content_140183249773656
            __token = 1859
            __token = 1891
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __token = 1946
            __content_140183249773656_1944 = _lookup_attr(_lookup_attr(getitem('industry'), 'perm_storage'), 'closure_counter')
            __content_140183249773656_1944 = __quote(__content_140183249773656_1944, '\x00', '&#0;', None, False)
            __token = 2037
            __content_140183249773656_2035 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656_2035 = __quote(__content_140183249773656_2035, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s%s%s%s%s' % ('\nswitch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_secondary_had_produced_check, LOAD_PERM(', (__content_140183249773656_1944 if (__content_140183249773656_1944 is not None) else ''), ')) {\n\t0..60: return CB_RESULT_IND_PROD_NO_CHANGE;\n\t', (__content_140183249773656_2035 if (__content_140183249773656_2035 is not None) else ''), '_secondary_close_random;\n}\n\n', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)

            # <Interpolation value=<Substitution '\nswitch(FEAT_INDUSTRIES, SELF, ${industry.id}_check_secondary_closure, allow_close_secondary) {\n\t1..255: ${industry.id}_secondary_had_produced_check;\n\treturn CB_RESULT_IND_PROD_NO_CHANGE;\n}\n\n\n' (43:80)> braces_required=True translation=False at 7f7ef3a79710> -> __content_140183249773656
            __token = 2158
            __token = 2190
            __content_140183249773656 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656 = __quote(__content_140183249773656, '\x00', '&#0;', None, False)
            __token = 2264
            __content_140183249773656_2262 = _lookup_attr(getitem('industry'), 'id')
            __content_140183249773656_2262 = __quote(__content_140183249773656_2262, '\x00', '&#0;', None, False)
            __content_140183249773656 = ('%s%s%s%s%s' % ('\nswitch(FEAT_INDUSTRIES, SELF, ', (__content_140183249773656 if (__content_140183249773656 is not None) else ''), '_check_secondary_closure, allow_close_secondary) {\n\t1..255: ', (__content_140183249773656_2262 if (__content_140183249773656_2262 is not None) else ''), '_secondary_had_produced_check;\n\treturn CB_RESULT_IND_PROD_NO_CHANGE;\n}\n\n\n', ))
            if (__content_140183249773656 is None):
                pass
            else:
                if (__content_140183249773656 is False):
                    __content_140183249773656 = None
                else:
                    __tt = type(__content_140183249773656)
                    if ((__tt is int) or (__tt is float) or (__tt is int)):
                        __content_140183249773656 = str(__content_140183249773656)
                    else:
                        if (__tt is bytes):
                            __content_140183249773656 = decode(__content_140183249773656)
                        else:
                            if (__tt is not str):
                                try:
                                    __content_140183249773656 = __content_140183249773656.__html__
                                except get('AttributeError', AttributeError):
                                    __converted = convert(__content_140183249773656)
                                    __content_140183249773656 = (str(__content_140183249773656) if (__content_140183249773656 is __converted) else __converted)
                                else:
                                    __content_140183249773656 = __content_140183249773656()
            if (__content_140183249773656 is not None):
                __append(__content_140183249773656)
        except:
            if (__token is not None):
                rcontext.setdefault('__error__', []).append((__tokens[__token] + (__filename, _exc_info()[1], )))
            raise
예제 #44
0
    def render(__stream,
               econtext,
               rcontext,
               __i18n_domain=None,
               __i18n_context=None):
        __append = __stream.append
        __re_amp = g_re_amp
        __token = None
        __re_needs_escape = g_re_needs_escape

        def __convert(target):
            if (target is None):
                return
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except AttributeError:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            target = target()
            return target

        def __quote(target, quote, quote_entity, default, default_marker):
            if (target is None):
                return
            if (target is default_marker):
                return default
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            return target()
                if (target is not None):
                    try:
                        escape = (__re_needs_escape(target) is not None)
                    except TypeError:
                        pass
                    else:
                        if escape:
                            if ('&' in target):
                                target = target.replace('&', '&amp;')
                            if ('<' in target):
                                target = target.replace('<', '&lt;')
                            if ('>' in target):
                                target = target.replace('>', '&gt;')
                            if ((quote is not None) and (quote in target)):
                                target = target.replace(quote, quote_entity)
            return target

        translate = econtext['__translate']
        decode = econtext['__decode']
        convert = econtext['__convert']
        on_error_handler = econtext['__on_error_handler']
        try:
            getitem = econtext.__getitem__
            get = econtext.get
            __append('\n\n')
            __append('\n\n')
            __append(
                '\nif (ttd_platform != PLATFORM_OPENTTD || openttd_version ')
            __append('<')
            __append(
                ' version_openttd(1, 7, 0, 27769)) {\n\terror(FATAL, REQUIRES_OPENTTD, string(STR_ERR_OPENTTD_VERSION));\n\texit;\n}\n\n'
            )
            __backup_incompatible_grf_139703132008120 = get(
                'incompatible_grf', __marker)

            # <Value 'incompatible_grfs' (14:48)> -> __iterator
            __token = 503
            __iterator = getitem('incompatible_grfs')
            (
                __iterator,
                ____index_139703105970416,
            ) = getitem('repeat')('incompatible_grf', __iterator)
            econtext['incompatible_grf'] = None
            for __item in __iterator:
                econtext['incompatible_grf'] = __item

                # <Interpolation value=<Substitution '\n    if (grf_future_status("${incompatible_grf.grfid}")) {\n        error(FATAL, string(STR_ERR_INCOMPATIBLE_SET, "${incompatible_grf.grfname}"));\n    }\n' (14:67)> braces_required=True translation=False at 7f0f2a0163c8> -> __content_139703124559104
                __token = 527
                __token = 552
                __content_139703124559104 = _lookup_attr(
                    getitem('incompatible_grf'), 'grfid')
                __content_139703124559104 = __quote(__content_139703124559104,
                                                    '\x00', '&#0;', None,
                                                    False)
                __token = 638
                __content_139703124559104_636 = _lookup_attr(
                    getitem('incompatible_grf'), 'grfname')
                __content_139703124559104_636 = __quote(
                    __content_139703124559104_636, '\x00', '&#0;', None, False)
                __content_139703124559104 = ('%s%s%s%s%s' % (
                    '\n    if (grf_future_status("',
                    (__content_139703124559104 if
                     (__content_139703124559104 is not None) else ''),
                    '")) {\n        error(FATAL, string(STR_ERR_INCOMPATIBLE_SET, "',
                    (__content_139703124559104_636 if
                     (__content_139703124559104_636 is not None) else ''),
                    '"));\n    }\n',
                ))
                if (__content_139703124559104 is None):
                    pass
                else:
                    if (__content_139703124559104 is False):
                        __content_139703124559104 = None
                    else:
                        __tt = type(__content_139703124559104)
                        if ((__tt is int) or (__tt is float) or (__tt is int)):
                            __content_139703124559104 = str(
                                __content_139703124559104)
                        else:
                            if (__tt is bytes):
                                __content_139703124559104 = decode(
                                    __content_139703124559104)
                            else:
                                if (__tt is not str):
                                    try:
                                        __content_139703124559104 = __content_139703124559104.__html__
                                    except get('AttributeError',
                                               AttributeError):
                                        __converted = convert(
                                            __content_139703124559104)
                                        __content_139703124559104 = (
                                            str(__content_139703124559104) if
                                            (__content_139703124559104 is
                                             __converted) else __converted)
                                    else:
                                        __content_139703124559104 = __content_139703124559104(
                                        )
                if (__content_139703124559104 is not None):
                    __append(__content_139703124559104)
                ____index_139703105970416 -= 1
                if (____index_139703105970416 > 0):
                    __append('')
            if (__backup_incompatible_grf_139703132008120 is __marker):
                del econtext['incompatible_grf']
            else:
                econtext[
                    'incompatible_grf'] = __backup_incompatible_grf_139703132008120
            __append('\n\n\n')
            __append(
                '\n/* this one might not survive as artic-only\nif (climate == CLIMATE_ARCTIC) {\n\tINCOMPATIBLE_GRF("mb\\07\\00", "Alpine Climate");\n}\n*/\n\nif (grf_future_status("MG\\08\\00", "\\FF\\FF\\FF\\00")) {\n\terror(FATAL, string(STR_ERR_INCOMPATIBLE_SET, "Lumber Mill"));\n}\n\nif (grf_future_status("CACa")) {\n\tif (param["CACa", 1] != 0) {\n\t\terror(FATAL, string(STR_ERR_INCOMPATIBLE_PARAM_CITYSET));\n\t}\n}\nif (grf_future_status("CASa")) {\n\tif (param["CASa", 1] != 0) {\n\t\terror(FATAL, string(STR_ERR_INCOMPATIBLE_PARAM_CANSET));\n\t}\n}\nif (grf_future_status("VC\\00\\01")) {\n\tif (param["VC\\00\\01", 254] '
            )
            __append('<')
            __append(
                '= 17) {\n\t\terror(FATAL, string(STR_ERR_INCOMPATIBLE_SET_TTRS_VERSION));\n\t}\n}\n'
            )
        except:
            if (__token is not None):
                rcontext.setdefault('__error__', []).append(
                    (__tokens[__token] + (
                        __filename,
                        _exc_info()[1],
                    )))
            raise
예제 #45
0
    def processTask(self, event, task, parent=None):  # noqa
        # XXX: C901: This has a high McCabe complexity score of 16.
        # TODO: Refactor this method.

        value = None
        try:
            value = next(task)
            if isinstance(value, CallValue):
                # Done here, next() will StopIteration anyway
                self.unregisterTask((event, task, parent))
                # We are in a callEvent
                value = parent.send(value.value)
                if isinstance(value, GeneratorType):
                    # We loose a yield but we gain one,
                    # we don't need to change
                    # event.waitingHandlers
                    # The below code is delegated to handlers
                    # in the waitEvent generator
                    # self.registerTask((event, value, parent))
                    task_state = next(value)
                    task_state["task_event"] = event
                    task_state["task"] = value
                    task_state["parent"] = parent
                else:
                    event.waitingHandlers -= 1
                    if value is not None:
                        event.value.value = value
                    self.registerTask((event, parent, None))
            elif isinstance(value, GeneratorType):
                event.waitingHandlers += 1
                self.unregisterTask((event, task, None))
                # First yielded value is always the task state
                task_state = next(value)
                task_state["task_event"] = event
                task_state["task"] = value
                task_state["parent"] = task
                # The below code is delegated to handlers
                # in the waitEvent generator
                # self.registerTask((event, value, task))
                # XXX: ^^^ Why is this commented out anyway?
            elif isinstance(value, ExceptionWrapper):
                self.unregisterTask((event, task, parent))
                if parent:
                    value = parent.throw(value.extract())
                    if value is not None:
                        value_generator = (val for val in (value,))
                        self.registerTask((event, value_generator, parent))
                else:
                    raise value.extract()
            elif isinstance(value, Sleep):
                if value is not task:
                    value.task = (event, task, parent)
                    self.registerTask((event, value, parent))
                    self.unregisterTask((event, task, parent))
            elif value is not None:
                event.value.value = value
        except StopIteration:
            event.waitingHandlers -= 1
            self.unregisterTask((event, task, parent))

            if parent:
                self.registerTask((event, parent, None))
            elif hasattr(task, "task"):
                # XXX: The subtask is considered a "waiting handler"
                event.waitingHandlers += 1
                self.registerTask(task.task)
            elif event.waitingHandlers == 0:
                event.value.inform(True)
                self._eventDone(event)
        except KeyboardInterrupt:
            self.stop()
        except SystemExit as e:
            self.stop(e.code)
        except:
            self.unregisterTask((event, task, parent))

            etype, evalue, etraceback = _exc_info()
            traceback = format_tb(etraceback)
            err = (etype, evalue, etraceback)

            event.value.value = err
            event.value.errors = True
            event.value.inform(True)

            if event.failure:
                self.fire(event.child("failure", event, err), *event.channels)

            self.fire(exception(etype, evalue, traceback, handler=None, fevent=event))
예제 #46
0
    def _dispatcher(self, event, channels, remaining):  # noqa
        # XXX: C901: This has a high McCabe complexity score of 22.
        # TODO: Refactor this method.

        if event.cancelled:
            return

        if event.complete:
            if not getattr(event, "cause", None):
                event.cause = event
            event.effects = 1  # event itself counts (must be done)
        eargs = event.args
        ekwargs = event.kwargs

        if self._cache_needs_refresh:
            # Don't call self._cache.clear() from other threads,
            # this may interfere with cache rebuild.
            self._cache.clear()
            self._cache_needs_refresh = False
        try:  # try/except is fastest if successful in most cases
            event_handlers = self._cache[(event.name, channels)]
        except KeyError:
            h = (self.getHandlers(event, channel) for channel in channels)

            event_handlers = sorted(chain(*h), key=attrgetter("priority"), reverse=True)

            if isinstance(event, generate_events):
                from .helpers import FallBackGenerator

                event_handlers.append(FallBackGenerator()._on_generate_events)
            elif isinstance(event, exception) and len(event_handlers) == 0:
                from .helpers import FallBackExceptionHandler

                event_handlers.append(FallBackExceptionHandler()._on_exception)
            elif isinstance(event, signal) and len(event_handlers) == 0:
                from .helpers import FallBackSignalHandler

                event_handlers.append(FallBackSignalHandler()._on_signal)

            self._cache[(event.name, channels)] = event_handlers

        if isinstance(event, generate_events):
            with self._lock:
                self._currently_handling = event
                if remaining > 0 or len(self._queue) or not self._running:
                    event.reduce_time_left(0)
                elif self._tasks:
                    event.reduce_time_left(TIMEOUT)
                # From now on, firing an event will reduce time left
                # to 0, which prevents event handlers from waiting (or wakes
                # them up with resume if they should be waiting already)
        else:
            self._currently_handling = event

        value = None
        err = None

        for event_handler in event_handlers:
            event.handler = event_handler
            try:
                if event_handler.event:
                    value = event_handler(event, *eargs, **ekwargs)
                else:
                    value = event_handler(*eargs, **ekwargs)
            except KeyboardInterrupt:
                self.stop()
            except SystemExit as e:
                self.stop(e.code)
            except:
                etype, evalue, etraceback = _exc_info()
                traceback = format_tb(etraceback)
                err = (etype, evalue, traceback)

                event.value.errors = True

                value = err

                if event.failure:
                    self.fire(event.child("failure", event, err), *event.channels)

                self.fire(exception(etype, evalue, traceback, handler=event_handler, fevent=event))

            if value is not None:
                if isinstance(value, GeneratorType):
                    event.waitingHandlers += 1
                    event.value.promise = True
                    self.registerTask((event, value, None))
                else:
                    event.value.value = value

            # it is kind of a temporal hack to allow processing
            # of tasks, added in one of event handlers here
            if isinstance(event, generate_events) and self._tasks:
                event.reduce_time_left(TIMEOUT)

            if event.stopped:
                break  # Stop further event processing

        self._currently_handling = None
        self._eventDone(event, err)
예제 #47
0
    def wrapper(*args, **kwargs):
        gen = genfunct(*args, **kwargs)
        _yieldingfrom[gen] = gen_yf = _stack()

        try:
            # if first poll of gen raises StopIteration
            # or any other Exception, we propagate
            item = gen.next()

            # OUTER loop
            while True:

                # yield _from(EXPR)
                # semantics based on PEP 380, Revised**12, 19 April
                if isinstance(item, _from):
                    _i, _iyf = item.iterator, None
                    try:
                        # first poll of the subiterator
                        _y = _i.next()
                    except StopIteration, _e:
                        # subiterator exhausted on first poll
                        # extract return value
                        _r = _e.args
                        if not _r: _r = (None,)
                    else:

                        # if subgenerator is another supergenerator
                        # extract the root of its gen_yf shared_stack
                        try:
                            _iyf = _i.gi_frame.f_locals['gen']
                        except (AttributeError,KeyError):
                            _iyf = []
                        else:
                            _iyf = _yieldingfrom.get(_iyf,[])
                            if isinstance(_iyf, _stack):
                                _iyf = _iyf.root()
                        gen_yf.push(_i, _iyf)

                        # INNER loop
                        while True:

                            if _iyf is None:
                                # subiterator was adopted by caller
                                # and is now exhausted
                                item = _y
                                break

                            try:
                                # yield what the subiterator did
                                _s = (yield _y)

                            except GeneratorExit, _e:
                                # close as many subiterators as possible
                                while gen_yf:
                                    _i, _iyf = gen_yf.top()
                                    try:
                                        _close = _i.close
                                    except AttributeError:
                                        pass
                                    else:
                                        _close()
                                    gen_yf.pop()
                                # finally clause will gen.close()
                                raise _e

                            except BaseException:
                                # caller did wrapper.throw
                                _x = _exc_info()
                                # throw to the subiterator if possible
                                while gen_yf:
                                    _i, _iyf = gen_yf.top()
                                    try:
                                        _throw = _i.throw
                                    except AttributeError:
                                        # doesn't attempt to close _i?
                                        # try throwing to subiterator's parent
                                        pass
                                    else:
                                        try:
                                            _y = _throw(*_x)
                                        except StopIteration, _e:
                                            _r = _e.args
                                            if not _r: _r = (None,)
                                            # drop to INTERSECTION A
                                            # then to INTERSECTION B
                                            break
                                        else:
                                            _r = None
                                            # drop to INTERSECTION A
                                            # then to INNER loop
                                            break
                                    gen_yf.pop()
예제 #48
0
def get_error_page(status, **kwargs):
    """Return an HTML page, containing a pretty error response.

    status should be an int or a str.
    kwargs will be interpolated into the page template.
    """
    try:
        code, reason, message = _httputil.valid_status(status)
    except ValueError:
        raise cherrypy.HTTPError(500, _exc_info()[1].args[0])

    # We can't use setdefault here, because some
    # callers send None for kwarg values.
    if kwargs.get('status') is None:
        kwargs['status'] = '%s %s' % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__

    for k, v in six.iteritems(kwargs):
        if v is None:
            kwargs[k] = ''
        else:
            kwargs[k] = escape_html(kwargs[k])

    # Use a custom template or callable for the error page?
    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')

    # Default template, can be overridden below.
    template = _HTTPErrorTemplate
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                # The caller function may be setting headers manually,
                # so we delegate to it completely. We may be returning
                # an iterator as well as a string here.
                #
                # We *must* make sure any content is not unicode.
                result = error_page(**kwargs)
                if cherrypy.lib.is_iterator(result):
                    from cherrypy.lib.encoding import UTF8StreamEncoder
                    return UTF8StreamEncoder(result)
                elif isinstance(result, six.text_type):
                    return result.encode('utf-8')
                else:
                    if not isinstance(result, bytes):
                        raise ValueError(
                            'error page function did not '
                            'return a bytestring, six.text_type or an '
                            'iterator - returned object of type %s.' %
                            (type(result).__name__))
                    return result
            else:
                # Load the template from this path.
                template = tonative(open(error_page, 'rb').read())
        except Exception:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += '<br />'
            m += 'In addition, the custom error page failed:\n<br />%s' % e
            kwargs['message'] = m

    response = cherrypy.serving.response
    response.headers['Content-Type'] = 'text/html;charset=utf-8'
    result = template % kwargs
    return result.encode('utf-8')
예제 #49
0
        else:
            kwargs[k] = _escape(kwargs[k])
    
    template = _HTTPErrorTemplate
    
    # Replace the default template with a custom one?
    error_page_file = cherrypy.request.error_page.get(code, '')
    if error_page_file:
        try:
            template = file(error_page_file, 'rb').read()
        except:
            m = kwargs['message']
            if m:
                m += "<br />"
            m += ("In addition, the custom error page "
                  "failed:\n<br />%s" % (_exc_info()[1]))
            kwargs['message'] = m
    
    return template % kwargs


_ie_friendly_error_sizes = {
    400: 512, 403: 256, 404: 512, 405: 256,
    406: 512, 408: 512, 409: 512, 410: 256,
    500: 512, 501: 512, 505: 512,
    }


def _be_ie_unfriendly(status):
    import cherrypy
    response = cherrypy.response
    def render(__stream,
               econtext,
               rcontext,
               __i18n_domain=None,
               __i18n_context=None):
        __append = __stream.append
        __re_amp = g_re_amp
        __token = None
        __re_needs_escape = g_re_needs_escape

        def __convert(target):
            if (target is None):
                return
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except AttributeError:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            target = target()
            return target

        def __quote(target, quote, quote_entity, default, default_marker):
            if (target is None):
                return
            if (target is default_marker):
                return default
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            return target()
                if (target is not None):
                    try:
                        escape = (__re_needs_escape(target) is not None)
                    except TypeError:
                        pass
                    else:
                        if escape:
                            if ('&' in target):
                                target = target.replace('&', '&amp;')
                            if ('<' in target):
                                target = target.replace('<', '&lt;')
                            if ('>' in target):
                                target = target.replace('>', '&gt;')
                            if ((quote is not None) and (quote in target)):
                                target = target.replace(quote, quote_entity)
            return target

        translate = econtext['__translate']
        decode = econtext['__decode']
        convert = econtext['__convert']
        on_error_handler = econtext['__on_error_handler']
        try:
            getitem = econtext.__getitem__
            get = econtext.get
            __append('cargotable {\n    ')
            __backup_cargo_139875096936064 = get('cargo', __marker)

            # <Value 'registered_cargos' (2:41)> -> __iterator
            __token = 54
            __iterator = getitem('registered_cargos')
            (
                __iterator,
                ____index_139875070542176,
            ) = getitem('repeat')('cargo', __iterator)
            econtext['cargo'] = None
            for __item in __iterator:
                econtext['cargo'] = __item

                # <Interpolation value=<Substitution '\n        ${cargo.cargo_label},\n    ' (2:60)> braces_required=True translation=False at 7f3733e48748> -> __content_139875089167952
                __token = 82
                __token = 84
                __content_139875089167952 = _lookup_attr(
                    getitem('cargo'), 'cargo_label')
                __content_139875089167952 = __quote(__content_139875089167952,
                                                    '\x00', '&#0;', None,
                                                    False)
                __content_139875089167952 = ('%s%s%s' % (
                    '\n        ',
                    (__content_139875089167952 if
                     (__content_139875089167952 is not None) else ''),
                    ',\n    ',
                ))
                if (__content_139875089167952 is None):
                    pass
                else:
                    if (__content_139875089167952 is False):
                        __content_139875089167952 = None
                    else:
                        __tt = type(__content_139875089167952)
                        if ((__tt is int) or (__tt is float) or (__tt is int)):
                            __content_139875089167952 = str(
                                __content_139875089167952)
                        else:
                            if (__tt is bytes):
                                __content_139875089167952 = decode(
                                    __content_139875089167952)
                            else:
                                if (__tt is not str):
                                    try:
                                        __content_139875089167952 = __content_139875089167952.__html__
                                    except get('AttributeError',
                                               AttributeError):
                                        __converted = convert(
                                            __content_139875089167952)
                                        __content_139875089167952 = (
                                            str(__content_139875089167952) if
                                            (__content_139875089167952 is
                                             __converted) else __converted)
                                    else:
                                        __content_139875089167952 = __content_139875089167952(
                                        )
                if (__content_139875089167952 is not None):
                    __append(__content_139875089167952)
                ____index_139875070542176 -= 1
                if (____index_139875070542176 > 0):
                    __append('')
            if (__backup_cargo_139875096936064 is __marker):
                del econtext['cargo']
            else:
                econtext['cargo'] = __backup_cargo_139875096936064
            __append('\n}\n\n')
            __append('\ndisable_item(FEAT_CARGOS, 0, 29);\n')
            __append('\ndisable_item(FEAT_CARGOS, 31, 31);\n\n')
            __backup_cargo_139875096950488 = get('cargo', __marker)

            # <Value 'registered_cargos' (12:26)> -> __iterator
            __token = 411
            __iterator = getitem('registered_cargos')
            (
                __iterator,
                ____index_139875070545872,
            ) = getitem('repeat')('cargo', __iterator)
            econtext['cargo'] = None
            for __item in __iterator:
                econtext['cargo'] = __item

                # <Interpolation value=<Substitution '\n    spriteset(cargoicon_${cargo.id}) {\n        [10 + 20 * ${cargo.icon_indices[0]}, 10 + 20 * ${cargo.icon_indices[1]}, 10, 10, 0, 0, ${"ANIM," if cargo.allow_animated_pixels else None} "src/graphics/other/cargoicons.png"]\n    }\n\n\n    ' (12:45)> braces_required=True translation=False at 7f3733e48dd8> -> __content_139875089167952
                __token = 435
                __token = 457
                __content_139875089167952 = _lookup_attr(
                    getitem('cargo'), 'id')
                __content_139875089167952 = __quote(__content_139875089167952,
                                                    '\x00', '&#0;', None,
                                                    False)
                __token = 491
                __content_139875089167952_489 = _lookup_attr(
                    getitem('cargo'), 'icon_indices')[0]
                __content_139875089167952_489 = __quote(
                    __content_139875089167952_489, '\x00', '&#0;', None, False)
                __token = 527
                __content_139875089167952_525 = _lookup_attr(
                    getitem('cargo'), 'icon_indices')[1]
                __content_139875089167952_525 = __quote(
                    __content_139875089167952_525, '\x00', '&#0;', None, False)
                __token = 567
                __content_139875089167952_565 = ('ANIM,' if _lookup_attr(
                    getitem('cargo'), 'allow_animated_pixels') else None)
                __content_139875089167952_565 = __quote(
                    __content_139875089167952_565, '\x00', '&#0;', None, False)
                __content_139875089167952 = ('%s%s%s%s%s%s%s%s%s' % (
                    '\n    spriteset(cargoicon_',
                    (__content_139875089167952 if
                     (__content_139875089167952 is not None) else ''),
                    ') {\n        [10 + 20 * ',
                    (__content_139875089167952_489 if
                     (__content_139875089167952_489 is not None) else ''),
                    ', 10 + 20 * ',
                    (__content_139875089167952_525 if
                     (__content_139875089167952_525 is not None) else ''),
                    ', 10, 10, 0, 0, ',
                    (__content_139875089167952_565 if
                     (__content_139875089167952_565 is not None) else ''),
                    ' "src/graphics/other/cargoicons.png"]\n    }\n\n\n    ',
                ))
                if (__content_139875089167952 is None):
                    pass
                else:
                    if (__content_139875089167952 is False):
                        __content_139875089167952 = None
                    else:
                        __tt = type(__content_139875089167952)
                        if ((__tt is int) or (__tt is float) or (__tt is int)):
                            __content_139875089167952 = str(
                                __content_139875089167952)
                        else:
                            if (__tt is bytes):
                                __content_139875089167952 = decode(
                                    __content_139875089167952)
                            else:
                                if (__tt is not str):
                                    try:
                                        __content_139875089167952 = __content_139875089167952.__html__
                                    except get('AttributeError',
                                               AttributeError):
                                        __converted = convert(
                                            __content_139875089167952)
                                        __content_139875089167952 = (
                                            str(__content_139875089167952) if
                                            (__content_139875089167952 is
                                             __converted) else __converted)
                                    else:
                                        __content_139875089167952 = __content_139875089167952(
                                        )
                if (__content_139875089167952 is not None):
                    __append(__content_139875089167952)
                __backup_economy_139875070628528 = get('economy', __marker)

                # <Value 'economies' (18:35)> -> __iterator
                __token = 697
                __iterator = getitem('economies')
                (
                    __iterator,
                    ____index_139875070544136,
                ) = getitem('repeat')('economy', __iterator)
                econtext['economy'] = None
                for __item in __iterator:
                    econtext['economy'] = __item
                    __append('\n        ')

                    # <Value 'cargo.id in economy.cargos' (19:36)> -> __condition
                    __token = 745
                    __condition = (_lookup_attr(getitem('cargo'), 'id')
                                   in _lookup_attr(getitem('economy'),
                                                   'cargos'))
                    if __condition:

                        # <Interpolation value=<Substitution '\n            if (economy==${economy.numeric_id}) {\n                ' (19:64)> braces_required=True translation=False at 7f3733e488d0> -> __content_139875089167952
                        __token = 786
                        __token = 801
                        __content_139875089167952 = _lookup_attr(
                            getitem('economy'), 'numeric_id')
                        __content_139875089167952 = __quote(
                            __content_139875089167952, '\x00', '&#0;', None,
                            False)
                        __content_139875089167952 = ('%s%s%s' % (
                            '\n            if (economy==',
                            (__content_139875089167952 if
                             (__content_139875089167952 is not None) else ''),
                            ') {\n                ',
                        ))
                        if (__content_139875089167952 is None):
                            pass
                        else:
                            if (__content_139875089167952 is False):
                                __content_139875089167952 = None
                            else:
                                __tt = type(__content_139875089167952)
                                if ((__tt is int) or (__tt is float)
                                        or (__tt is int)):
                                    __content_139875089167952 = str(
                                        __content_139875089167952)
                                else:
                                    if (__tt is bytes):
                                        __content_139875089167952 = decode(
                                            __content_139875089167952)
                                    else:
                                        if (__tt is not str):
                                            try:
                                                __content_139875089167952 = __content_139875089167952.__html__
                                            except get('AttributeError',
                                                       AttributeError):
                                                __converted = convert(
                                                    __content_139875089167952)
                                                __content_139875089167952 = (
                                                    str(__content_139875089167952
                                                        ) if
                                                    (__content_139875089167952
                                                     is __converted) else
                                                    __converted)
                                            else:
                                                __content_139875089167952 = __content_139875089167952(
                                                )
                        if (__content_139875089167952 is not None):
                            __append(__content_139875089167952)
                        __backup_macroname_139875070585480 = get(
                            'macroname', __marker)

                        # <Static value=<_ast.Str object at 0x7f3733e48cc0> name=None at 7f3733e48be0> -> __value
                        __value = _static_139875070545088
                        econtext['macroname'] = __value

                        # <Value 'load: cargo_props.pynml' (21:46)> -> __macro
                        __token = 870
                        __macro = ' cargo_props.pynml'
                        __macro = __loader(__macro)
                        __token = 870
                        __m = __macro.include
                        __m(__stream, econtext.copy(), rcontext, __i18n_domain)
                        econtext.update(rcontext)
                        if (__backup_macroname_139875070585480 is __marker):
                            del econtext['macroname']
                        else:
                            econtext[
                                'macroname'] = __backup_macroname_139875070585480
                        __append('\n            }\n        ')
                    __append('\n    ')
                    ____index_139875070544136 -= 1
                    if (____index_139875070544136 > 0):
                        __append('')
                if (__backup_economy_139875070628528 is __marker):
                    del econtext['economy']
                else:
                    econtext['economy'] = __backup_economy_139875070628528
                __append('\n')
                ____index_139875070545872 -= 1
                if (____index_139875070545872 > 0):
                    __append('')
            if (__backup_cargo_139875096950488 is __marker):
                del econtext['cargo']
            else:
                econtext['cargo'] = __backup_cargo_139875096950488
            __append('\n')
        except:
            if (__token is not None):
                rcontext.setdefault('__error__', []).append(
                    (__tokens[__token] + (
                        __filename,
                        _exc_info()[1],
                    )))
            raise
예제 #51
0
 def error(self):
     """
     Logs the current exception info
     """
     exc = _exc_info()
     self.logger.error("".join(_traceback.format_exception(*exc)))
예제 #52
0
파일: thread_io.py 프로젝트: rawler/bhindex
 def run(self):
     try:
         self.result = self.target(*self.args, **self.kwargs)
     except:
         self.result = _exc_info()
         _print_exception(*self.result)
예제 #53
0
        if v is None:
            kwargs[k] = ""
        else:
            kwargs[k] = _escape(kwargs[k])
    
    # Use a custom template or callable for the error page?
    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')
    if error_page:
        try:
            if callable(error_page):
                return error_page(**kwargs)
            else:
                return open(error_page, 'rb').read() % kwargs
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += "<br />"
            m += "In addition, the custom error page failed:\n<br />%s" % e
            kwargs['message'] = m
    
    return _HTTPErrorTemplate % kwargs


_ie_friendly_error_sizes = {
    400: 512, 403: 256, 404: 512, 405: 256,
    406: 512, 408: 512, 409: 512, 410: 256,
    500: 512, 501: 512, 505: 512,
    }
예제 #54
0
def get_error_page(status, errors=None, **kwargs):
    """Return an HTML page, containing a pretty error response.

    status should be an int or a str.
    kwargs will be interpolated into the page template.
    """
    try:
        code, reason, message = _httputil.valid_status(status)
    except ValueError:
        raise cherrypy.HTTPError(500, _exc_info()[1].args[0])

    # We can't use setdefault here, because some
    # callers send None for kwarg values.
    if kwargs.get('status') is None:
        kwargs['status'] = '%s %s' % (code, reason)
    if kwargs.get('message') is None:
        kwargs['message'] = message
    if kwargs.get('traceback') is None:
        kwargs['traceback'] = ''
    if kwargs.get('version') is None:
        kwargs['version'] = cherrypy.__version__

    for k, v in kwargs.items():
        if v is None:
            kwargs[k] = ''
        else:
            kwargs[k] = _escape(kwargs[k])

    # Use a custom template or callable for the error page?
    pages = cherrypy.serving.request.error_page
    error_page = pages.get(code) or pages.get('default')

    # Default template, can be overridden below.
    template = _HTTPErrorTemplate
    if error_page:
        try:
            if hasattr(error_page, '__call__'):
                # The caller function may be setting headers manually,
                # so we delegate to it completely. We may be returning
                # an iterator as well as a string here.
                #
                # We *must* make sure any content is not unicode.
                result = error_page(errors=errors, **kwargs)
                if cherrypy.lib.is_iterator(result):
                    return UTF8StreamEncoder(result)
                elif isinstance(result, str):  # str is OK for Python3
                    return result.encode('utf-8')
                else:
                    if not isinstance(result, bytes):
                        raise ValueError(
                            'error page function did not '
                            'return a bytestring, unicodestring or an '
                            'iterator - returned object of type {}.'
                            .format(type(result).__name__))
                    return result
            else:
                # Load the template from this path.
                template = tonative(open(error_page, 'rb').read())
        except:
            e = _format_exception(*_exc_info())[-1]
            m = kwargs['message']
            if m:
                m += '<br />'
            m += 'In addition, the custom error page failed:\n<br />%s' % e
            kwargs['message'] = m

    response = cherrypy.serving.response
    response.headers['Content-Type'] = 'text/html;charset=utf-8'
    result = template % kwargs
    return result.encode('utf-8')
예제 #55
0
    def send(self, event, channel, target=None, errors=False, log=True):
        """Send a new Event to Event Handlers for the Target and Channel

        This will send the given Event, to the spcified CHannel on the
        Target Component's Channel.

        if target is None, then target will be set as the Channel of
        the current Component, self.channel (defaulting back to None).

        If this Component's Manager is itself, enqueue on this Component's
        Event Queue, otherwise enqueue on this Component's Manager.

        @param event: The Event Object
        @type  event: Event

        @param channel: The Channel this Event is bound for
        @type  channel: str

        @keyword target: The target Component's channel this Event is bound for
        @type    target: str or Component

        @keyword errors: True to raise errors, False otherwise
        @type    errors: bool

        @keyword log: True to log errors, False otherwise
        @type    log: bool

        @return: The return value of the last executed Event Handler
        @rtype:  object
        """

        if target is None:
            target = getattr(self, "channel", None)

        if self.manager == self:
            event.channel = channel
            event.target = target
            eargs = event.args
            ekwargs = event.kwargs
            if target is not None and isinstance(target, Component):
                target = getattr(target, "channel", None)
            if target is not None and type(target) == str:
                channel = "%s:%s" % (target, channel)

            r = False
            for handler in self._getHandlers(channel):
                try:
                    if handler._passEvent:
                        r = partial(handler, event, *eargs, **ekwargs)()
                    else:
                        r = partial(handler, *eargs, **ekwargs)()
                except (KeyboardInterrupt, SystemExit):
                    raise
                except:
                    if log:
                        self.push(Error(*_exc_info()), "error")
                    if errors:
                        raise
                    else:
                        _exc_clear()
                if r is not None and r and handler.filter:
                    return r
            return r
        else:
            return self.manager.send(event, channel, target, errors, log)
예제 #56
0
파일: hub.py 프로젝트: HVF/gevent
 def _start(self):
     try:
         greenlet = self.greenlet_class(self.handle)
         greenlet.switch()
     except:
         self.hub.handle_error(None, *sys._exc_info())
예제 #57
0
    def render(__stream,
               econtext,
               rcontext,
               __i18n_domain=None,
               __i18n_context=None):
        __append = __stream.append
        __re_amp = g_re_amp
        __token = None
        __re_needs_escape = g_re_needs_escape

        def __convert(target):
            if (target is None):
                return
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except AttributeError:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            target = target()
            return target

        def __quote(target, quote, quote_entity, default, default_marker):
            if (target is None):
                return
            if (target is default_marker):
                return default
            __tt = type(target)
            if ((__tt is int) or (__tt is float) or (__tt is int)):
                target = str(target)
            else:
                if (__tt is bytes):
                    target = decode(target)
                else:
                    if (__tt is not str):
                        try:
                            target = target.__html__
                        except:
                            __converted = convert(target)
                            target = (str(target) if
                                      (target is __converted) else __converted)
                        else:
                            return target()
                if (target is not None):
                    try:
                        escape = (__re_needs_escape(target) is not None)
                    except TypeError:
                        pass
                    else:
                        if escape:
                            if ('&' in target):
                                target = target.replace('&', '&amp;')
                            if ('<' in target):
                                target = target.replace('<', '&lt;')
                            if ('>' in target):
                                target = target.replace('>', '&gt;')
                            if ((quote is not None) and (quote in target)):
                                target = target.replace(quote, quote_entity)
            return target

        translate = econtext['__translate']
        decode = econtext['__decode']
        convert = econtext['__convert']
        on_error_handler = econtext['__on_error_handler']
        try:
            getitem = econtext.__getitem__
            get = econtext.get

            # <Static value=<_ast.Dict object at 0x10c4f1cc0> name=None at 10c4f1f60> -> __attrs_4503365728
            __attrs_4503365728 = _static_4501478592

            # <html ... (0:0)
            # --------------------------------------------------------
            __append('<html')
            __append('>')
            __append('\n')

            # <Static value=<_ast.Dict object at 0x10c4f1cc0> name=None at 10c4f1f60> -> __attrs_4503366456
            __attrs_4503366456 = _static_4501478592

            # <head ... (0:0)
            # --------------------------------------------------------
            __append('<head')
            __append('>')
            __append('\n  ')

            # <Static value=<_ast.Dict object at 0x10c4f1cc0> name=None at 10c4f1f60> -> __attrs_4503367240
            __attrs_4503367240 = _static_4501478592

            # <title ... (0:0)
            # --------------------------------------------------------
            __append('<title')
            __append('>')
            __append('Welcome to POLL!')
            __append('</title>')
            __append('\n')
            __append('</head>')
            __append('\n')

            # <Static value=<_ast.Dict object at 0x10c4f1cc0> name=None at 10c4f1f60> -> __attrs_4503413032
            __attrs_4503413032 = _static_4501478592

            # <body ... (0:0)
            # --------------------------------------------------------
            __append('<body')
            __append('>')
            __append('\n\n')

            # <Static value=<_ast.Dict object at 0x10c4f1cc0> name=None at 10c4f1f60> -> __attrs_4503413760
            __attrs_4503413760 = _static_4501478592

            # <h2 ... (0:0)
            # --------------------------------------------------------
            __append('<h2')
            __append('>')
            __append('Welcome to POLL!')
            __append('</h2>')
            __append('\n\n')
            __append('</body>')
            __append('\n')
            __append('</html>')
        except:
            if (__token is not None):
                rcontext.setdefault('__error__', []).append(
                    (__tokens[__token] + (
                        __filename,
                        _exc_info()[1],
                    )))
            raise
예제 #58
0
파일: hub.py 프로젝트: erics8/wwqLyParse
 def _start(self):
     try:
         greenlet = self.greenlet_class(self.handle)
         greenlet.switch()
     except: # pylint:disable=bare-except
         self.hub.handle_error(None, *sys._exc_info()) # pylint:disable=no-member