Пример #1
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)
Пример #2
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)
Пример #3
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'])
Пример #5
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'])
Пример #6
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)]
Пример #7
0
 def fetch(self, url):
     try:
         return urlopen('http://127.0.0.1:%d/%s' % (self.port, url)).read()
     except Exception:
         return repr(_e())