示例#1
0
文件: errors.py 项目: Belsepubi/naali
    def __init__(self, request, response, status, message=None, error=None):
        super(HTTPError, self).__init__(request, response,
                status, message=message, error=error)

        response.close = True

        self.request = request
        self.response = response
        self.status = status

        short, long = RESPONSES.get(status, ("???", "???",))
        self.message = message or short

        self.error = error
        if self.error is not None:
            self.etype, self.evalue, self.traceback = self.error
            traceback = ["ERROR: %s\n" % str(self.evalue)]
            traceback.extend(format_tb(self.traceback))
        else:
            self.etype, self.evalue, self.traceback = None, None, None
            traceback = []

        response.status = "%s %s" % (status, short)

        response.body = DEFAULT_ERROR_MESSAGE % {
            "status": "%s %s" % (status, short),
            "message": _escape(message) if message else "",
            "traceback": "".join(traceback),
            "version": SERVER_VERSION}
示例#2
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
示例#3
0
 def test_FailingBehavior(self):
     if PY2:
         from cgi import escape as _escape
     else:
         from html import escape as _escape
     template = Cheetah.Template.Template(
         "$escape($request)",
         searchList=[{
             'escape':
             lambda s, _escape=_escape: _escape(s, quote=False),
             'request':
             'foobar'
         }])
     assert template
     self.assertRaises(AttributeError, template.respond)
示例#4
0
 def test_FailingBehaviorWithSetting(self):
     if PY2:
         from cgi import escape as _escape
     else:
         from html import escape as _escape
     template = Cheetah.Template.Template(
         "$escape($request)",
         searchList=[{
             'escape':
             lambda s, _escape=_escape: _escape(s, quote=False),
             'request':
             'foobar'
         }],
         compilerSettings={'prioritizeSearchListOverSelf': True})
     assert template
     assert template.respond()
示例#5
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
示例#6
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
示例#7
0
    def __init__(self, request, response, status, message=None, error=None):
        super(HTTPError, self).__init__(request,
                                        response,
                                        status,
                                        message=message,
                                        error=error)

        response.close = True

        self.request = request
        self.response = response
        self.status = status

        short, long = RESPONSES.get(status, (
            "???",
            "???",
        ))
        self.message = message or short

        self.error = error
        if self.error is not None:
            self.etype, self.evalue, self.traceback = self.error
            traceback = ["ERROR: %s\n" % str(self.evalue)]
            traceback.extend(self.traceback)
        else:
            self.etype, self.evalue, self.traceback = None, None, None
            traceback = []

        response.status = "%s %s" % (status, short)

        response.body = DEFAULT_ERROR_MESSAGE % {
            "status": "%s %s" % (status, short),
            "message": _escape(message) if message else "",
            "traceback": "".join(traceback),
            "version": SERVER_VERSION
        }
示例#8
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')

    # 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_typeing 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:
            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')
 # 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.iteritems():
     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 />"
示例#10
0
def html_repr(object):
    so = _escape(repr(object))
    if hasattr(object, 'hyper_respond'):
        return '<a href="/status/object/%d/">%s</a>' % (id(object), so)
    else:
        return so
示例#11
0
 def findfile(self, request):
     for handler in self.handlers:
         if handler.can_handle(request):
             return handler.handle_request(request)
     request.path = _escape(request.path)
     return error(request, 404, "File " + request.path + " not found")
示例#12
0
def handle_request(handler, request, form):

    global session_cookies_live_secs, session_check_period, last_session_check_time

    act_time = _time.time()
    path, params, query, fragment = split_uri(request)

    ip = request.request_headers.get("x-forwarded-for", None)
    if ip is None:
        with _suppress(Exception, warn=False):
            ip = request.channel.addr[0]
    if ip:
        request.channel.addr = (ip, request.channel.addr[1])

    request.log()

    # COMPAT: new param style like flask
    if query is not None:
        args = _athana.AthanaHandler.parse_query(query)
    else:
        args = []
    # /COMPAT
    path = _urllib.unquote(path)
    if params is not None:
        params = _urllib.unquote(params)
    if fragment is not None:
        fragment = _urllib.unquote(fragment)

    cookies = {}
    if "cookie" in request.request_headers:
        cookiestr = request.request_headers["cookie"]
        if cookiestr.rfind(";") == len(cookiestr) - 1:
            cookiestr = cookiestr[:-1]
        items = cookiestr.split(';')
        for a in items:
            a = a.strip()
            i = a.find('=')
            if i > 0:
                key, value = a[:i], a[i + 1:]
                cookies[key] = value
            else:
                _logg.warn("corrupt cookie value: %s",
                           a.encode("string-escape"))

    request.Cookies = cookies

    sessionid = None

    if "PSESSION" in cookies:
        sessionid = cookies["PSESSION"]

    session_expiration_time = act_time - session_cookies_live_secs
    session = None
    if sessionid is None:

        if act_time - last_session_check_time > session_check_period:
            # delete all sessions with lastuse older than act_time - session_cookies_live_secs
            sessionids_to_be_deleted = [
                sid for sid in handler.sessions
                if handler.sessions[sid].lastuse < session_expiration_time
            ]
            for sid in sessionids_to_be_deleted:
                del handler.sessions[sid]
            last_session_check_time = act_time

        sessionid = handler.create_session_id()
        _logg.debug("Creating new session %s", sessionid)

    else:
        if sessionid in handler.sessions:
            session = handler.sessions[sessionid]
            if session.lastuse < session_expiration_time:
                del handler.sessions[sessionid]
                session = None
            else:
                session.use()

    if session is None:
        session = _athana.Session(sessionid)
        handler.sessions[sessionid] = session

    request['Content-Type'] = 'text/html; encoding=utf-8; charset=utf-8'

    maxlen = -1
    context = None
    global contexts
    for c in contexts:
        if path.startswith(c.name) and len(c.name) > maxlen:
            context = c
            maxlen = len(context.name)

    if context is None:
        error(request, 404)
        return

    fullpath = path
    path = path[len(context.name):]
    if len(path) == 0 or path[0] != '/':
        path = "/" + path

    request.session = session
    request.sessionid = sessionid
    request.context = context
    request.path = path
    request.fullpath = fullpath
    request.paramstring = params
    request.query = query
    request.fragment = fragment

    # COMPAT: new param style like flask
    # we don't need this for WSGI, args / form parsing is done by the WSGI app
    if not isinstance(context, _athana.WSGIContext):
        form, files = _athana.filter_out_files(form)
        try:
            request.args = make_param_dict_utf8_values(args)
            if "csrf_token" in request.args:
                form.append(('csrf_token', str(request.args["csrf_token"])))
            request.form = make_param_dict_utf8_values(form)
        except UnicodeDecodeError:
            return error(request, 400)

        if form and request.method == 'POST':
            if 'csrf_token' not in request.form:
                raise ValueError("csrf_token not in form of request path " +
                                 request.fullpath)
            else:
                session.mediatum_form.csrf_token.process_data(
                    request.form["csrf_token"].replace("!!!!!", "##"))
                session.mediatum_form.validate()

        request.csrf_token = session.mediatum_form.csrf_token
        request.files = _ImmutableMultiDict(files)
        make_legacy_params_dict(request)

    # /COMPAT
    request.request = request
    request.ip = ip
    request.uri = request.uri.replace(context.name, "/")
    request._split_uri = None

    request.channel.current_request = None

    if path == "/threadstatus":
        return _athana.thread_status(request)
    if path == "/profilingstatus":
        return _athana.profiling_status(request)

    function = context.match(path)

    if function is None:
        _logg.debug("Request %s matches no pattern (context: %s)",
                    request.path, context.name)
        request.path = _escape(request.path)
        return error(request, 404, "File %s not found" % request.path)
    if _athana.multithreading_enabled:
        handler.queuelock.acquire()
        handler.queue += [(function, request)]
        handler.queuelock.release()
    else:
        _athana.call_handler_func(function, request)
def _force_to_latin1(x):
    return 'nonunicode data: %s...' % _escape(x[:100].decode('latin1'))
def _to_js(x, default_nonunicode_formatter, formatter=None, as_string=False):
    """Formats given x into js-parseable structure.

  Args:
    x: describes the data
    default_nonunicode_formatter: The default formatter to use for non-Unicode.
    formatter: function-like object that takes x and returns html string.
    as_string: force the value to be a string in the JSON.

  Returns:
    string - the javascript representation
  """
    if formatter is not None:
        x = formatter(x)
    # Making the output a list, causes datatable interpret its elements
    # as html, rather than text.
    if hasattr(x, '__html__'):
        x = x.__html__()
    elif hasattr(x, '_repr_html_'):
        x = x._repr_html_()  # pylint: disable=protected-access

    # These converters are meant to produce reasonable values
    # but for anything customizables users should just create per-type
    # converters in interactive_table.DEFAULT_FORMATTERS
    if _is_numpy_type(x) and hasattr(x, 'dtype'):
        if x.dtype.kind == 'M':
            x = str(_pd.to_datetime(x))
        elif x.shape:
            # Convert lists into their string representations
            x = str(x)
        elif x.dtype.kind == 'b':
            x = bool(x)
        elif type(x).__name__.startswith('float'):
            if hasattr(x, 'is_integer') and x.is_integer():
                x = int(x)
            else:
                x = float(x)
        elif type(x).__name__ in _NP_INT_TYPES:
            x = int(x)
    if isinstance(x, _six.integer_types) and abs(x) > 2**52:
        x = '%d' % x
    represent_as_string = lambda x: _escape(str(x))
    if isinstance(x, dict) and not isinstance(x, _CellValue):
        # dictionaries need to be converted to string, if not they will be passed
        # verbatim to json and they will be shown as Object on javascript side.
        # Note: this keeps x as json-able object, so it will ignore default=
        # encode below and we don't do double encoding.
        x = represent_as_string(x)

    if isinstance(x, list):
        # If this is a list of dictionaries, we need to convert each dict to
        # a string.
        if all((isinstance(el, dict) and not isinstance(el, _CellValue)
                for el in x)):
            x = [represent_as_string(elem) for elem in x]

    # Ensure that we're returning JSON of a string value.
    double_encode_json = as_string and not isinstance(x, _six.string_types)

    try:
        result = _json.dumps(x, default=represent_as_string)
    except UnicodeDecodeError:
        if isinstance(x, _six.string_types):
            result = _json.dumps(default_nonunicode_formatter(x))
        else:
            result = _json.dumps(
                [_to_js(el, default_nonunicode_formatter) for el in x])
    result = result.replace('</', '<\\/')
    if double_encode_json:
        result = _json.dumps(result)
    return result
示例#15
0
def _code(S, doRepr = False): # convert a variable name or value to html
    if doRepr: S = repr(S)
    return "<code class='gmi'>" + _escape(str(S)) + "</code>"
示例#16
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')
示例#17
0
文件: html.py 项目: ForkRepo/sentry
 def escape(value):
     return _escape(value, True)