Ejemplo n.º 1
0
 def _handle(self, environ):
     try:
         environ['bottle.app'] = self
         request.bind(environ)
         response.bind()
         route, args = self.router.match(environ)
         environ['route.handle'] = route
         environ['bottle.route'] = route
         environ['route.url_args'] = args
         out = route.call(**args)
         if isinstance(out, asyncio.Future) or inspect.isgenerator(out):
             out = yield from out
         return out
     except HTTPResponse:
         return _e()
     except RouteReset:
         route.reset()
         return (yield from self._handle(environ))
     except (KeyboardInterrupt, SystemExit, MemoryError):
         raise
     except Exception:
         if not self.catchall: raise
         stacktrace = format_exc()
         environ['wsgi.errors'].write(stacktrace)
         return HTTPError(500, "Internal Server Error", _e(), stacktrace)
Ejemplo n.º 2
0
    def _handle(self, environ):
        path = environ['bottle.raw_path'] = environ['PATH_INFO']
        try:
            environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
        except UnicodeError:
            return HTTPError(400, 'Invalid path string. Expected UTF-8')

        try:
            environ['bottle.app'] = self
            request.bind(environ)
            response.bind()
            try:
                self.trigger_hook("before_request")
                route, args = self.router.match(environ)
                environ['route.handle'] = route
                environ['bottle.route'] = route
                environ['route.url_args'] = args
                out = route.call(**args)
                if isinstance(out, asyncio.Future) or inspect.isgenerator(out):
                    out = yield from out
                return out
            finally:
                self.trigger_hook("after_request")
        except HTTPResponse:
            return _e()
        except RouteReset:
            route.reset()
            return (yield from self._handle(environ))
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception:
            if not self.catchall: raise
            stacktrace = format_exc()
            environ['wsgi.errors'].write(stacktrace)
            return HTTPError(500, "Internal Server Error", _e(), stacktrace)
Ejemplo n.º 3
0
    def _handle(self, environ):
        path = environ['bottle.raw_path'] = environ['PATH_INFO']
        try:
            environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
        except UnicodeError:
            return HTTPError(400, 'Invalid path string. Expected UTF-8')

        try:
            environ['bottle.app'] = self
            request.bind(environ)
            response.bind()
            try:
                self.trigger_hook("before_request")
                route, args = self.router.match(environ)
                environ['route.handle'] = route
                environ['bottle.route'] = route
                environ['route.url_args'] = args
                out = route.call(**args)
                if isinstance(out, asyncio.Future) or inspect.isgenerator(out):
                    out = yield from out
                return out
            finally:
                self.trigger_hook("after_request")
        except HTTPResponse:
            return _e()
        except RouteReset:
            route.reset()
            return (yield from self._handle(environ))
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception:
            if not self.catchall: raise
            stacktrace = format_exc()
            environ['wsgi.errors'].write(stacktrace)
            return HTTPError(500, "Internal Server Error", _e(), stacktrace)
Ejemplo n.º 4
0
 def wsgi(self, environ, start_response):
     """ The bottle WSGI-interface. """
     try:
         out = self._cast((yield from self._handle(environ)))
         # rfc2616 section 4.3
         if response._status_code in (100, 101, 204, 304)\
         or environ['REQUEST_METHOD'] == 'HEAD':
             if hasattr(out, 'close'): out.close()
             out = []
         start_response(response._status_line, response.headerlist)
         return out
     except (KeyboardInterrupt, SystemExit, MemoryError):
         raise
     except Exception:
         if not self.catchall: raise
         err = '<h1>Critical error while processing request: %s</h1>' \
               % html_escape(environ.get('PATH_INFO', '/'))
         if DEBUG:
             err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                    '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                    % (html_escape(repr(_e())), html_escape(format_exc()))
         environ['wsgi.errors'].write(err)
         headers = [('Content-Type', 'text/html; charset=UTF-8')]
         start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
         return [tob(err)]
Ejemplo n.º 5
0
    def __call__(self, environ, start_response):
        try:
            return self.app(environ, start_response)
        except (Exception, ExceptionInBackend) as e:
            template_vars = {}
            if "bottle.request.post" in environ:
                environ["bottle.request.post"] = dict(
                    filter_sensitive_params(environ["bottle.request.post"], self.sensitive_params)
                )
            # update environ
            environ["foris.version"] = current_state.foris_version
            environ["foris.language"] = current_state.language
            environ["foris.backend"] = current_state.backend

            template_vars["environ"] = html_escape(pformat(environ))
            # Handles backend exceptions in same manner as
            if isinstance(e, ExceptionInBackend):
                error = "Remote Exception: %s" % e.remote_description
                extra = "<h3>Remote request</h3><pre>%s</pre>" % html_escape(json.dumps(e.query))
                trace = e.remote_stacktrace
            else:
                error = repr(_e())
                trace = format_exc()
                extra = ""
            template_vars["error"] = html_escape(error)
            template_vars["trace"] = html_escape(trace)
            template_vars["extra"] = extra
            template_vars["dump_file"] = "%s/%s" % (get_root(), self.dump_file)
            environ["wsgi.errors"].write(format_exc())
            headers = [("Content-Type", "text/html; charset=UTF-8")]
            err = ERROR_TEMPLATE % template_vars
            start_response("500 INTERNAL SERVER ERROR", headers)
            with open("/tmp/%s" % self.dump_file, "wb") as f:
                f.write(err.encode("UTF-8"))
            return [tob(err)]
Ejemplo n.º 6
0
 def wsgi(self, environ, start_response):
     """ The bottle WSGI-interface. """
     try:
         out = self._cast((yield from self._handle(environ)))
         # rfc2616 section 4.3
         if response._status_code in (100, 101, 204, 304)\
         or environ['REQUEST_METHOD'] == 'HEAD':
             if hasattr(out, 'close'): out.close()
             out = []
         start_response(response._status_line, response.headerlist)
         return out
     except (KeyboardInterrupt, SystemExit, MemoryError):
         raise
     except Exception:
         if not self.catchall: raise
         err = '<h1>Critical error while processing request: %s</h1>' \
               % html_escape(environ.get('PATH_INFO', '/'))
         if DEBUG:
             err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                    '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                    % (html_escape(repr(_e())), html_escape(format_exc()))
         environ['wsgi.errors'].write(err)
         headers = [('Content-Type', 'text/html; charset=UTF-8')]
         start_response('500 INTERNAL SERVER ERROR', headers,
                        sys.exc_info())
         return [tob(err)]
 def test_redirect_preserve_cookies(self):
     env = {'SERVER_PROTOCOL':'HTTP/1.1'}
     request.bind(env)
     bottle.response.bind()
     try:
         bottle.response.set_cookie('xxx', 'yyy')
         bottle.redirect('...')
     except bottle.HTTPResponse:
         h = [v for (k, v) in _e().headerlist if k == 'Set-Cookie']
         self.assertEqual(h, ['xxx=yyy'])
Ejemplo n.º 8
0
 def test_redirect_preserve_cookies(self):
     env = {'SERVER_PROTOCOL': 'HTTP/1.1'}
     request.bind(env)
     bottle.response.bind()
     try:
         bottle.response.set_cookie('xxx', 'yyy')
         bottle.redirect('...')
     except bottle.HTTPResponse:
         h = [v for (k, v) in _e().headerlist if k == 'Set-Cookie']
         self.assertEqual(h, ['xxx=yyy'])
Ejemplo n.º 9
0
 def assertRedirect(self, target, result, query=None, status=303, **args):
     env = {'SERVER_PROTOCOL': 'HTTP/1.1'}
     for key in list(args):
         if key.startswith('wsgi'):
             args[key.replace('_', '.', 1)] = args[key]
             del args[key]
     env.update(args)
     request.bind(env)
     try:
         bottle.redirect(target, **(query or {}))
     except bottle.HTTPResponse:
         r = _e()
         self.assertEqual(status, r.status_code)
         self.assertTrue(r.headers)
         self.assertEqual(result, r.headers['Location'])
Ejemplo n.º 10
0
 def assertRedirect(self, target, result, query=None, status=303, **args):
     env = {'SERVER_PROTOCOL':'HTTP/1.1'}
     for key in args:
         if key.startswith('wsgi'):
             args[key.replace('_', '.', 1)] = args[key]
             del args[key]
     env.update(args)
     request.bind(env)
     try:
         bottle.redirect(target, **(query or {}))
     except bottle.HTTPResponse:
         r = _e()
         self.assertEqual(status, r.status)
         self.assertTrue(r.headers)
         self.assertEqual(result, r.headers['Location'])
Ejemplo n.º 11
0
        def wrapper(*a, **ka):
            try:
                rv = callback(*a, **ka)
            except HTTPError:
                rv = _e()

            if isinstance(rv, dict):
                # Attempt to serialize, raises exception on failure
                try:
                    json_response = dumps(rv)
                except UnicodeDecodeError:
                    json_response = dumps(rv, encoding="gbk")
                # Set content type only if serialization succesful
                response.content_type = 'application/json'
                return json_response
            elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
                rv.body = dumps(rv.body)
                rv.content_type = 'application/json'
            return rv
Ejemplo n.º 12
0
 def __call__(self, environ, start_response):
     try:
         return self.app(environ, start_response)
     except Exception:
         template_vars = {}
         if 'bottle.request.post' in environ:
             environ['bottle.request.post'] = dict(
                 filter_sensitive_params(environ['bottle.request.post'],
                                         self.sensitive_params))
         template_vars['environ'] = html_escape(pformat(environ))
         template_vars['error'] = html_escape(repr(_e()))
         template_vars['trace'] = html_escape(format_exc())
         template_vars['dump_file'] = self.dump_file
         environ['wsgi.errors'].write(format_exc())
         headers = [('Content-Type', 'text/html; charset=UTF-8')]
         err = ERROR_TEMPLATE % template_vars
         start_response('500 INTERNAL SERVER ERROR', headers)
         with open("/tmp/%s" % self.dump_file, "w") as f:
             f.write(err)
         return [tob(err)]
Ejemplo n.º 13
0
 def __call__(self, environ, start_response):
     try:
         return self.app(environ, start_response)
     except Exception:
         template_vars = {}
         if 'bottle.request.post' in environ:
             environ['bottle.request.post'] = dict(
                 filter_sensitive_params(environ['bottle.request.post'],
                                         self.sensitive_params))
         template_vars['environ'] = html_escape(pformat(environ))
         template_vars['error'] = html_escape(repr(_e()))
         template_vars['trace'] = html_escape(format_exc())
         template_vars['dump_file'] = self.dump_file
         environ['wsgi.errors'].write(format_exc())
         headers = [('Content-Type', 'text/html; charset=UTF-8')]
         err = ERROR_TEMPLATE % template_vars
         start_response('500 INTERNAL SERVER ERROR', headers)
         with open("/tmp/%s" % self.dump_file, "w") as f:
             f.write(err)
         return [tob(err)]
Ejemplo n.º 14
0
 def fetch(self, url):
     try:
         return urlopen('http://127.0.0.1:%d/%s' % (self.port, url), None,
                        5).read()
     except Exception:
         return repr(_e())
Ejemplo n.º 15
0
 def fetch(self, url):
     try:
         return urlopen('http://127.0.0.1:%d/%s' % (self.port, url)).read()
     except Exception:
         return repr(_e())