def cpexception(): cherrypy.response.status = 500 if sys.version_info < (3, 0): cherrypy.response.body = bytes( pages.get_template('errors/cperror.html').render( e=_cperror.format_exc())) else: cherrypy.response.body = bytes( pages.get_template('errors/cperror.html').render( e=_cperror.format_exc()), 'utf8')
def handle_error(): cherrypy.response.status = 500 cherrypy.response.body = bytes( "<html><body>Sorry, an error occured</body></html>", encoding='utf-8') print('-' * 80) print(datetime.now()) print(_cperror.format_exc()) with open('errors.log', 'a') as f: print('-' * 80, file=f) print(datetime.now(), file=f) print(_cperror.format_exc(), file=f)
def run(): end = time.time() - start print 'Started in %s seconds' % end if '--null' in opts: print '\nUsing null Request object' try: run_standard_benchmarks() except: print _cperror.format_exc() raise finally: cherrypy.engine.exit()
def cpexception(): cherrypy.response.status = 500 try: cherrypy.response.body = bytes( pages.get_template('errors/cperror.html').render( e=_cperror.format_exc(), mk=mako.exceptions.html_error_template().render().decode( )), 'utf8') except: cherrypy.response.body = bytes( pages.get_template('errors/cperror.html').render( e=_cperror.format_exc(), mk=""), 'utf8')
def run(): end = time.time() - start print 'Started in %s seconds' % end if '--null' in opts: print '\nUsing null Request object' try: run_standard_benchmarks() except: print _cperror.format_exc() raise finally: cherrypy.engine.exit()
def run(): end = time.time() - start print("Started in %s seconds" % end) if "--null" in opts: print("\nUsing null Request object") try: try: run_standard_benchmarks() except: print _cperror.format_exc() raise finally: cherrypy.engine.exit()
def run(): end = time.time() - start print("Started in %s seconds" % end) if "--null" in opts: print("\nUsing null Request object") try: try: run_standard_benchmarks() except: print _cperror.format_exc() raise finally: cherrypy.engine.exit()
def run(self): # Parse output of ab, setting attributes on self try: self.output = _cpmodpy.read_process(AB_PATH or "ab", self.args()) except: print _cperror.format_exc() raise for attr, name, pattern in self.parse_patterns: val = re.search(pattern, self.output, re.MULTILINE) if val: val = val.group(1) setattr(self, attr, val) else: setattr(self, attr, None)
def run(self): # Parse output of ab, setting attributes on self try: self.output = _cpmodpy.read_process(AB_PATH or "ab", self.args()) except: print _cperror.format_exc() raise for attr, name, pattern in self.parse_patterns: val = re.search(pattern, self.output, re.MULTILINE) if val: val = val.group(1) setattr(self, attr, val) else: setattr(self, attr, None)
def run(self): global AB_PATH try: self.output = _cpmodpy.read_process(AB_PATH or 'ab', self.args()) except: print _cperror.format_exc() raise for attr, name, pattern in self.parse_patterns: val = re.search(pattern, self.output, re.MULTILINE) if val: val = val.group(1) setattr(self, attr, val) else: setattr(self, attr, None)
def run(self): global AB_PATH try: self.output = _cpmodpy.read_process(AB_PATH or 'ab', self.args()) except: print _cperror.format_exc() raise for attr, name, pattern in self.parse_patterns: val = re.search(pattern, self.output, re.MULTILINE) if val: val = val.group(1) setattr(self, attr, val) else: setattr(self, attr, None)
def logError(self, msg = '', context = '', severity = logging.INFO, traceback = False): if traceback: msg += _cperror.format_exc() context = context if context else self.context self.logger.error_log.log(severity, '[%+25.25s] %s' % (context[-25:], msg))
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except: tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = '' s, h, b = _cperror.bare_error(tb) if self.started_response: self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except: _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return ''.join(b) else: return b
def error_page(self): cherrypy.response.status = 500 if self.config['_debug']: cherrypy.response.body = _cperror.get_error_page(status=500, traceback=_cperror.format_exc()) else: cherrypy.response.body = '<html><body>Error</body></html>'
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except: tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = '' s, h, b = _cperror.bare_error(tb) if self.started_response: self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except: _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return ''.join(b) else: return b
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except: tb = _cperror.format_exc() #print('trapped (started %s):' % self.started_response, tb) _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = "" s, h, b = _cperror.bare_error(tb) if self.started_response: # Empty our iterable (so future calls raise StopIteration) self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return "".join(b) else: return b
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except: tb = _cperror.format_exc() #print('trapped (started %s):' % self.started_response, tb) _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = "" s, h, b = _cperror.bare_error(tb) if self.started_response: # Empty our iterable (so future calls raise StopIteration) self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return ntob("").join(b) else: return b
def respond(self): req = self.req try: local = req.server.bind_addr local = httputil.Host(local[0], local[1], '') remote = (req.conn.remote_addr, req.conn.remote_port) remote = httputil.Host(remote[0], remote[1], '') scheme = req.scheme sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = req.method path = req.path qs = req.qs or '' headers = req.inheaders.items() rfile = req.rfile prev = None try: redirections = [] while True: request, response = app.get_serving( local, remote, scheme, 'HTTP/1.1') request.multithread = True request.multiprocess = False request.app = app request.prev = prev try: request.run(method, path, qs, req.request_protocol, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not self.recursive: if ir.path in redirections: raise RuntimeError( 'InternalRedirector visited the same URL twice: %r' % ir.path) else: if qs: qs = '?' + qs redirections.append(sn + path + qs) method = 'GET' path = ir.path qs = ir.query_string rfile = BytesIO() self.send_response(response.output_status, response.header_list, response.body) finally: app.release_serving() except: tb = format_exc() cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b)
def my_log_traceback(severity=logging.CRITICAL): """Write the last error's headers and traceback to the cherrypy error log witih a CRITICAL severity.""" from cherrypy import _cperror h = [" %s: %s" % (k, v) for k, v in cherrypy.request.header_list] cherrypy.log('\nRequest Headers:\n' + '\n'.join(h) + '\n\n' + _cperror.format_exc(), "HTTP", severity=severity)
def error(self, msg='', context='', severity=logging.INFO, traceback=False): if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
def error(self, msg='', context='', severity=logging.INFO, traceback=False): """Write to the error log. This is not just for errors! Applications may call this at any time to log application-specific information. """ if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
def error(self, msg='', context='', severity=logging.DEBUG, traceback=False): """Write to the 'error' log. This is not just for errors! Applications may call this at any time to log application-specific information. """ if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
def respond(self): req = self.req try: local = req.server.bind_addr local = httputil.Host(local[0], local[1], '') remote = (req.conn.remote_addr, req.conn.remote_port) remote = httputil.Host(remote[0], remote[1], '') scheme = req.scheme sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = req.method path = req.path qs = req.qs or '' headers = req.inheaders.items() rfile = req.rfile prev = None try: redirections = [] while True: request, response = app.get_serving(local, remote, scheme, 'HTTP/1.1') request.multithread = True request.multiprocess = False request.app = app request.prev = prev try: request.run(method, path, qs, req.request_protocol, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not self.recursive: if ir.path in redirections: raise RuntimeError('InternalRedirector visited the same URL twice: %r' % ir.path) else: if qs: qs = '?' + qs redirections.append(sn + path + qs) method = 'GET' path = ir.path qs = ir.query_string rfile = BytesIO() self.send_response(response.output_status, response.header_list, response.body) finally: app.release_serving() except: tb = format_exc() cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b)
def error(self, msg='', context='', severity=logging.INFO, traceback=False): """Write the given ``msg`` to the error log. This is not just for errors! Applications may call this at any time to log application-specific information. If ``traceback`` is True, the traceback of the current exception (if any) will be appended to ``msg``. """ if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
def error(self, msg='', context='', severity=logging.INFO, traceback=False): """Write the given ``msg`` to the error log. This is not just for errors! Applications may call this at any time to log application-specific information. If ``traceback`` is True, the traceback of the current exception (if any) will be appended to ``msg``. """ if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
def logError(self, msg='', context='', severity=logging.INFO, traceback=False): if traceback: msg += _cperror.format_exc() context = context if context else self.context self.logger.error_log.log(severity, '[%+25.25s] %s' % (context[-25:], msg))
def __call__(self, environ, start_response): """ Called as part of the WSGI stack to log the incoming request and its response using the common log format. If an error bubbles up to this middleware, we log it as such. """ try: response = self.app(environ, start_response) self.access(environ, response) return response except: self.error(traceback=True) return HttpResponseServerError(_cperror.format_exc())
def __call__(self, environ: dict[str, str], start_response: Callable) -> HttpResponse: """ Called as part of the WSGI stack to log the incoming request and its response using the common log format. If an error bubbles up to this middleware, we log it as such. """ try: response = self.app(environ, start_response) self.access(environ, response) return response except Exception: self.error(traceback=True, severity=logging.CRITICAL) return HttpResponseServerError(_cperror.format_exc())
def __call__(self, environ, start_response): """ Called as part of the WSGI stack to log the incoming request and its response using the common log format. If an error bubbles up to this middleware, we log it as such. """ try: response = self.app(environ, start_response) self.access(environ, response) return response except: self.error(traceback=True) return HttpResponseServerError(_cperror.format_exc())
def run(self, method, path, query_string, req_protocol, headers, rfile): response = cherrypy.serving.response self.stage = 'run' try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = path or '/' self.query_string = query_string or '' self.params = {} rp = (int(req_protocol[5]), int(req_protocol[7])) sp = (int(self.server_protocol[5]), int(self.server_protocol[7])) self.protocol = min(rp, sp) response.headers.protocol = self.protocol url = path if query_string: url += '?' + query_string self.request_line = '%s %s %s' % (method, url, req_protocol) self.header_list = list(headers) self.headers = httputil.HeaderMap() self.rfile = rfile self.body = None self.cookie = SimpleCookie() self.handler = None self.script_name = self.app.script_name self.path_info = pi = path[len(self.script_name):] self.stage = 'respond' self.respond(pi) except self.throws: raise except: if self.throw_errors: raise else: cherrypy.log(traceback=True, severity=40) if self.show_tracebacks: body = format_exc() else: body = '' r = bare_error(body) response.output_status, response.header_list, response.body = r if self.method == 'HEAD': response.body = [] try: cherrypy.log.access() except: cherrypy.log.error(traceback=True) if response.timed_out: raise cherrypy.TimeoutError() return response
def run(self, method, path, query_string, req_protocol, headers, rfile): response = cherrypy.serving.response self.stage = 'run' try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = path or '/' self.query_string = query_string or '' self.params = {} rp = (int(req_protocol[5]), int(req_protocol[7])) sp = (int(self.server_protocol[5]), int(self.server_protocol[7])) self.protocol = min(rp, sp) response.headers.protocol = self.protocol url = path if query_string: url += '?' + query_string self.request_line = '%s %s %s' % (method, url, req_protocol) self.header_list = list(headers) self.headers = httputil.HeaderMap() self.rfile = rfile self.body = None self.cookie = SimpleCookie() self.handler = None self.script_name = self.app.script_name self.path_info = pi = path[len(self.script_name):] self.stage = 'respond' self.respond(pi) except self.throws: raise except: if self.throw_errors: raise else: cherrypy.log(traceback=True, severity=40) if self.show_tracebacks: body = format_exc() else: body = '' r = bare_error(body) response.output_status, response.header_list, response.body = r if self.method == 'HEAD': response.body = [] try: cherrypy.log.access() except: cherrypy.log.error(traceback=True) if response.timed_out: raise cherrypy.TimeoutError() return response
def __init__(self, environ, start_response, cpapp): try: self.request = self.get_engine_request(environ, cpapp) meth = environ['REQUEST_METHOD'] path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '') qs = environ.get('QUERY_STRING', '') rproto = environ.get('SERVER_PROTOCOL') headers = self.translate_headers(environ) rfile = environ['wsgi.input'] response = self.request.run(meth, path, qs, rproto, headers, rfile) s, h, b = response.status, response.header_list, response.body exc = None except self.throws: self.close() raise except: if getattr(self.request, "throw_errors", False): self.close() raise tb = _cperror.format_exc() _cherrypy.log(tb) if not getattr(self.request, "show_tracebacks", True): tb = "" s, h, b = _cperror.bare_error(tb) exc = _sys.exc_info() self.iter_response = iter(b) try: start_response(s, h, exc) except self.throws: self.close() raise except: if getattr(self.request, "throw_errors", False): self.close() raise _cherrypy.log(traceback=True) self.close() # CherryPy test suite expects bare_error body to be output, # so don't call start_response (which, according to PEP 333, # may raise its own error at that point). s, h, b = _cperror.bare_error() self.iter_response = iter(b)
def errorPage(self, **kwargs): self.logger.debug(_cperror.format_exc()) try: args = { "message": kwargs['status'], "details": "Please consult the log files for more information.", "hint": '', "automatic_reload": False, } exception_class = _cperror._exc_info()[0] if issubclass(exception_class, DatabaseError): args[ 'details'] = "An database error occured, please consult the log files." args[ 'hint'] = "Maybe the database schema needs to be updated after an code update?" elif args["message"].startswith("4"): args["details"] = kwargs["message"] try: template_context, category_dict, run = self.category.prepareDisplay( ) template_context.update(args) filename = os.path.join( hf.hf_dir, hf.config.get("paths", "hf_template_dir"), "error.html") template = Template(filename=filename, lookup=hf.template_lookup) return template.render_unicode( **template_context).encode("utf-8") except Exception, e: self.logger.debug("Fancy error page generation failed\n" + traceback.format_exc()) filename = os.path.join( hf.hf_dir, hf.config.get("paths", "hf_template_dir"), "plain_error.html") template = Template(filename=filename, lookup=hf.template_lookup) return template.render_unicode(**args).encode("utf-8") except Exception, e: self.logger.error(u"error page generation failed: " + unicode(e)) self.logger.error(traceback.format_exc()) return u"""<h1>Error Inception</h1> <p>An error occured while displaying an error. Embarrasing.</p> <p>Please consult the log files!</p>""".encode("utf-8")
def get_pretty_errors(exc): import traceback try: text = cgitb.text(exc) html = cgitb.html(exc) except: # errors might be thrown when cgitb tries to inspect stuff, # in which case just get a regular stacktrace from cherrypy._cperror import format_exc text = format_exc(exc) html = None name = traceback.format_exception(*exc)[-1] return name, text, html
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except Exception: tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = '' s, h, b = _cperror.bare_error(tb) if six.PY3: # What fun. s = s.decode('ISO-8859-1') h = [ (k.decode('ISO-8859-1'), v.decode('ISO-8859-1')) for k, v in h ] if self.started_response: # Empty our iterable (so future calls raise StopIteration) self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except Exception: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return b''.join(b) else: return b
def trap(self, func, *args, **kwargs): try: return func(*args, **kwargs) except self.throws: raise except StopIteration: raise except Exception: tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: tb = '' s, h, b = _cperror.bare_error(tb) if six.PY3: # What fun. s = s.decode('ISO-8859-1') h = [ (k.decode('ISO-8859-1'), v.decode('ISO-8859-1')) for k, v in h ] if self.started_response: # Empty our iterable (so future calls raise StopIteration) self.iter_response = iter([]) else: self.iter_response = iter(b) try: self.start_response(s, h, _sys.exc_info()) except Exception: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40) raise if self.started_response: return ntob('').join(b) else: return b
def setapp(self): try: self.request = self.get_request() s, h, b = self.get_response() self.iter_response = iter(b) self.__add_write_hook(s, h, None) except self.throws: self.close() raise except _cherrypy.InternalRedirect as ir: self.environ[ 'cherrypy.previous_request'] = _cherrypy.serving.request self.close() self.iredirect(ir.path, ir.query_string) return except: if getattr(self.request, "throw_errors", False): self.close() raise tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not getattr(self.request, "show_tracebacks", True): tb = "" s, h, b = _cperror.bare_error(tb) self.iter_response = iter(b) try: self.__add_write_hook(s, h, _sys.exc_info()) except: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40) self.close() raise
def errorPage(self, **kwargs): self.logger.debug(_cperror.format_exc()) try: args = { "message": kwargs['status'], "details": "Please consult the log files for more information.", "hint": '', "automatic_reload": False, } exception_class = _cperror._exc_info()[0] if issubclass(exception_class, DatabaseError): args['details'] = "An database error occured, please consult the log files." args['hint'] = "Maybe the database schema needs to be updated after an code update?" elif args["message"].startswith("4"): args["details"] = kwargs["message"] try: template_context, category_dict, run = self.category.prepareDisplay() template_context.update(args) filename = os.path.join(hf.hf_dir, hf.config.get("paths", "hf_template_dir"), "error.html") template = Template(filename=filename, lookup=hf.template_lookup) return template.render_unicode(**template_context).encode("utf-8") except Exception, e: self.logger.debug("Fancy error page generation failed\n" + traceback.format_exc()) filename = os.path.join(hf.hf_dir, hf.config.get("paths", "hf_template_dir"), "plain_error.html") template = Template(filename=filename, lookup=hf.template_lookup) return template.render_unicode(**args).encode("utf-8") except Exception, e: self.logger.error(u"error page generation failed: " + unicode(e)) self.logger.error(traceback.format_exc()) return u"""<h1>Error Inception</h1> <p>An error occured while displaying an error. Embarrasing.</p> <p>Please consult the log files!</p>""".encode("utf-8")
def run(self, method, path, query_string, req_protocol, headers, rfile): r"""Process the Request. (Core) method, path, query_string, and req_protocol should be pulled directly from the Request-Line (e.g. "GET /path?key=val HTTP/1.0"). path This should be %XX-unquoted, but query_string should not be. When using Python 2, they both MUST be byte strings, not unicode strings. When using Python 3, they both MUST be unicode strings, not byte strings, and preferably not bytes \x00-\xFF disguised as unicode. headers A list of (name, value) tuples. rfile A file-like object containing the HTTP request entity. When run() is done, the returned object should have 3 attributes: * status, e.g. "200 OK" * header_list, a list of (name, value) tuples * body, an iterable yielding strings Consumer code (HTTP servers) should then access these response attributes to build the outbound stream. """ response = cherrypy.serving.response self.stage = "run" try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = path or "/" self.query_string = query_string or "" self.params = {} # Compare request and server HTTP protocol versions, in case our # server does not support the requested protocol. Limit our output # to min(req, server). We want the following output: # request server actual written supported response # protocol protocol response protocol feature set # a 1.0 1.0 1.0 1.0 # b 1.0 1.1 1.1 1.0 # c 1.1 1.0 1.0 1.0 # d 1.1 1.1 1.1 1.1 # Notice that, in (b), the response will be "HTTP/1.1" even though # the client only understands 1.0. RFC 2616 10.5.6 says we should # only return 505 if the _major_ version is different. rp = int(req_protocol[5]), int(req_protocol[7]) sp = int(self.server_protocol[5]), int(self.server_protocol[7]) self.protocol = min(rp, sp) response.headers.protocol = self.protocol # Rebuild first line of the request (e.g. "GET /path HTTP/1.0"). url = path if query_string: url += "?" + query_string self.request_line = "%s %s %s" % (method, url, req_protocol) self.header_list = list(headers) self.headers = httputil.HeaderMap() self.rfile = rfile self.body = None self.cookie = SimpleCookie() self.handler = None # path_info should be the path from the # app root (script_name) to the handler. self.script_name = self.app.script_name self.path_info = pi = path[len(self.script_name) :] self.stage = "respond" self.respond(pi) except self.throws: raise except: if self.throw_errors: raise else: # Failure in setup, error handler or finalize. Bypass them. # Can't use handle_error because we may not have hooks yet. cherrypy.log(traceback=True, severity=40) if self.show_tracebacks: body = format_exc() else: body = "" r = bare_error(body) response.output_status, response.header_list, response.body = r if self.method == "HEAD": # HEAD requests MUST NOT return a message-body in the response. response.body = [] try: cherrypy.log.access() except: cherrypy.log.error(traceback=True) if response.timed_out: raise cherrypy.TimeoutError() return response
def respond(self): req = self.req try: # Obtain a Request object from CherryPy local = req.server.bind_addr local = httputil.Host(local[0], local[1], "") remote = req.conn.remote_addr, req.conn.remote_port remote = httputil.Host(remote[0], remote[1], "") scheme = req.scheme sn = cherrypy.tree.script_name(req.uri or "/") if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = req.method path = req.path qs = req.qs or "" headers = req.inheaders.items() rfile = req.rfile prev = None try: redirections = [] while True: request, response = app.get_serving( local, remote, scheme, "HTTP/1.1") request.multithread = True request.multiprocess = False request.app = app request.prev = prev # Run the CherryPy Request object and obtain the # response try: request.run(method, path, qs, req.request_protocol, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not self.recursive: if ir.path in redirections: raise RuntimeError( "InternalRedirector visited the same " "URL twice: %r" % ir.path) else: # Add the *previous* path_info + qs to # redirections. if qs: qs = "?" + qs redirections.append(sn + path + qs) # Munge environment and try again. method = "GET" path = ir.path qs = ir.query_string rfile = io.BytesIO() self.send_response( response.output_status, response.header_list, response.body) finally: app.release_serving() except: tb = format_exc() # print tb cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b)
def handler(req): from mod_python import apache try: global _isSetUp if not _isSetUp: setup(req) _isSetUp = True # Obtain a Request object from CherryPy local = req.connection.local_addr local = http.Host(local[0], local[1], req.connection.local_host or "") remote = req.connection.remote_addr remote = http.Host(remote[0], remote[1], req.connection.remote_host or "") scheme = req.parsed_uri[0] or 'http' req.get_basic_auth_pw() try: # apache.mpm_query only became available in mod_python 3.1 q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: bad_value = ("You must provide a PythonOption '%s', " "either 'on' or 'off', when running a version " "of mod_python < 3.1") threaded = options.get('multithread', '').lower() if threaded == 'on': threaded = True elif threaded == 'off': threaded = False else: raise ValueError(bad_value % "multithread") forked = options.get('multiprocess', '').lower() if forked == 'on': forked = True elif forked == 'off': forked = False else: raise ValueError(bad_value % "multiprocess") sn = cherrypy.tree.script_name(req.uri or "/") if sn is None: send_response(req, '404 Not Found', [], '') else: app = cherrypy.tree.apps[sn] method = req.method path = req.uri qs = req.args or "" sproto = req.protocol headers = req.headers_in.items() rfile = _ReadOnlyRequest(req) prev = None redirections = [] while True: request = cherrypy.engine.request(local, remote, scheme) request.login = req.user request.multithread = bool(threaded) request.multiprocess = bool(forked) request.app = app request.prev = prev # Run the CherryPy Request object and obtain the response try: response = request.run(method, path, qs, sproto, headers, rfile) break except cherrypy.InternalRedirect, ir: cherrypy.engine.release() prev = request if not recursive: if ir.path in redirections: raise RuntimeError( "InternalRedirector visited the " "same URL twice: %r" % ir.path) else: # Add the *previous* path_info + qs to redirections. if qs: qs = "?" + qs redirections.append(sn + path + qs) # Munge environment and try again. method = "GET" path = ir.path qs = ir.query_string rfile = StringIO.StringIO() send_response(req, response.status, response.header_list, response.body) cherrypy.engine.release() except: tb = format_exc() cherrypy.log(tb) s, h, b = bare_error() send_response(req, s, h, b) return apache.OK
self.__add_write_hook(s, h, None) except self.throws: self.close() raise except _cherrypy.InternalRedirect, ir: self.environ[ 'cherrypy.previous_request'] = _cherrypy.serving.request self.close() self.iredirect(ir.path, ir.query_string) return except: if getattr(self.request, "throw_errors", False): self.close() raise tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not getattr(self.request, "show_tracebacks", True): tb = "" s, h, b = _cperror.bare_error(tb) self.iter_response = iter(b) try: self.__add_write_hook(s, h, _sys.exc_info()) except: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40)
def handle_error(): cherrypy.response.status = 500 logger.error("500 Error: %s" % _cperror.format_exc()) cherrypy.response.body = ["<html><body>Sorry, an error occured</body></html>"]
def cpexception(): cherrypy.response.status = 500 if sys.version_info < (3,0): cherrypy.response.body= bytes(pages.get_template('errors/cperror.html').render(e=_cperror.format_exc())) else: cherrypy.response.body= bytes(pages.get_template('errors/cperror.html').render(e=_cperror.format_exc()),'utf8')
def handle_error(): cherrypy.response.status = 500 cherrypy.response.body = ["<html><body>Sorry, an error occured</body></html>"] publisher.error('Request: '+ str(cherrypy.request.params) + '\n' +_cperror.format_exc())
def handler(req): global _isSetUp from mod_python import apache try: if not _isSetUp: setup(req) _isSetUp = True local = req.connection.local_addr local = httputil.Host(local[0], local[1], req.connection.local_host or '') remote = req.connection.remote_addr remote = httputil.Host(remote[0], remote[1], req.connection.remote_host or '') scheme = req.parsed_uri[0] or 'http' req.get_basic_auth_pw() try: q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: bad_value = "You must provide a PythonOption '%s', either 'on' or 'off', when running a version of mod_python < 3.1" threaded = options.get('multithread', '').lower() if threaded == 'on': threaded = True elif threaded == 'off': threaded = False else: raise ValueError(bad_value % 'multithread') forked = options.get('multiprocess', '').lower() if forked == 'on': forked = True elif forked == 'off': forked = False else: raise ValueError(bad_value % 'multiprocess') sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: send_response(req, '404 Not Found', [], '') else: app = cherrypy.tree.apps[sn] method = req.method path = req.uri qs = req.args or '' reqproto = req.protocol headers = copyitems(req.headers_in) rfile = _ReadOnlyRequest(req) prev = None try: redirections = [] while True: request, response = app.get_serving(local, remote, scheme, 'HTTP/1.1') request.login = req.user request.multithread = bool(threaded) request.multiprocess = bool(forked) request.app = app request.prev = prev try: request.run(method, path, qs, reqproto, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not recursive: if ir.path in redirections: raise RuntimeError('InternalRedirector visited the same URL twice: %r' % ir.path) else: if qs: qs = '?' + qs redirections.append(sn + path + qs) method = 'GET' path = ir.path qs = ir.query_string rfile = BytesIO() send_response(req, response.status, response.header_list, response.body, response.stream) finally: app.release_serving() except: tb = format_exc() cherrypy.log(tb, 'MOD_PYTHON', severity=logging.ERROR) s, h, b = bare_error() send_response(req, s, h, b) return apache.OK
def error(self, msg = '', context = '', severity = logging.INFO, traceback = False): if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
self.iter_response = iter(b) self.__add_write_hook(s, h, None) except self.throws: self.close() raise except _cherrypy.InternalRedirect, ir: self.environ['cherrypy.previous_request'] = _cherrypy.serving.request self.close() self.iredirect(ir.path, ir.query_string) return except: if getattr(self.request, "throw_errors", False): self.close() raise tb = _cperror.format_exc() _cherrypy.log(tb, severity=40) if not getattr(self.request, "show_tracebacks", True): tb = "" s, h, b = _cperror.bare_error(tb) self.iter_response = iter(b) try: self.__add_write_hook(s, h, _sys.exc_info()) except: # "The application must not trap any exceptions raised by # start_response, if it called start_response with exc_info. # Instead, it should allow such exceptions to propagate # back to the server or gateway." # But we still log and call close() to clean up ourselves. _cherrypy.log(traceback=True, severity=40)
def handle_error(): cherrypy.response.status = 500 tmpl = lookup.get_template("error.mako") details = _cperror.format_exc().replace("\n", "<br/>") return tmpl.render(details=details)
def handle_error(): cherrypy.response.status = httplib.INTERNAL_SERVER_ERROR cherrypy.response.body = "Internal Server Error" print(_cperror.format_exc())
def handle_error(): cherrypy.response.status = 500 cherrypy.response.body = [env.get_template('error.html').render({'error':_cperror.format_exc()}) ]
def run(self, method, path, query_string, req_protocol, headers, rfile): r"""Process the Request. (Core) method, path, query_string, and req_protocol should be pulled directly from the Request-Line (e.g. "GET /path?key=val HTTP/1.0"). path This should be %XX-unquoted, but query_string should not be. When using Python 2, they both MUST be byte strings, not unicode strings. When using Python 3, they both MUST be unicode strings, not byte strings, and preferably not bytes \x00-\xFF disguised as unicode. headers A list of (name, value) tuples. rfile A file-like object containing the HTTP request entity. When run() is done, the returned object should have 3 attributes: * status, e.g. "200 OK" * header_list, a list of (name, value) tuples * body, an iterable yielding strings Consumer code (HTTP servers) should then access these response attributes to build the outbound stream. """ response = cherrypy.serving.response self.stage = 'run' try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = path or "/" self.query_string = query_string or '' self.params = {} # Compare request and server HTTP protocol versions, in case our # server does not support the requested protocol. Limit our output # to min(req, server). We want the following output: # request server actual written supported response # protocol protocol response protocol feature set # a 1.0 1.0 1.0 1.0 # b 1.0 1.1 1.1 1.0 # c 1.1 1.0 1.0 1.0 # d 1.1 1.1 1.1 1.1 # Notice that, in (b), the response will be "HTTP/1.1" even though # the client only understands 1.0. RFC 2616 10.5.6 says we should # only return 505 if the _major_ version is different. rp = int(req_protocol[5]), int(req_protocol[7]) sp = int(self.server_protocol[5]), int(self.server_protocol[7]) self.protocol = min(rp, sp) response.headers.protocol = self.protocol # Rebuild first line of the request (e.g. "GET /path HTTP/1.0"). url = path if query_string: url += '?' + query_string self.request_line = '%s %s %s' % (method, url, req_protocol) self.header_list = list(headers) self.headers = httputil.HeaderMap() self.rfile = rfile self.body = None self.cookie = SimpleCookie() self.handler = None # path_info should be the path from the # app root (script_name) to the handler. self.script_name = self.app.script_name self.path_info = pi = path[len(self.script_name):] self.stage = 'respond' self.respond(pi) except self.throws: raise except: if self.throw_errors: raise else: # Failure in setup, error handler or finalize. Bypass them. # Can't use handle_error because we may not have hooks yet. cherrypy.log(traceback=True, severity=40) if self.show_tracebacks: body = format_exc() else: body = "" r = bare_error(body) response.output_status, response.header_list, response.body = r if self.method == "HEAD": # HEAD requests MUST NOT return a message-body in the response. response.body = [] try: cherrypy.log.access() except: cherrypy.log.error(traceback=True) if response.timed_out: raise cherrypy.TimeoutError() return response
def handler(req): from mod_python import apache try: global _isSetUp if not _isSetUp: setup(req) _isSetUp = True # Obtain a Request object from CherryPy local = req.connection.local_addr local = http.Host(local[0], local[1], req.connection.local_host or "") remote = req.connection.remote_addr remote = http.Host(remote[0], remote[1], req.connection.remote_host or "") scheme = req.parsed_uri[0] or 'http' req.get_basic_auth_pw() try: # apache.mpm_query only became available in mod_python 3.1 q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: bad_value = ("You must provide a PythonOption '%s', " "either 'on' or 'off', when running a version " "of mod_python < 3.1") threaded = options.get('multithread', '').lower() if threaded == 'on': threaded = True elif threaded == 'off': threaded = False else: raise ValueError(bad_value % "multithread") forked = options.get('multiprocess', '').lower() if forked == 'on': forked = True elif forked == 'off': forked = False else: raise ValueError(bad_value % "multiprocess") sn = cherrypy.tree.script_name(req.uri or "/") if sn is None: send_response(req, '404 Not Found', [], '') else: app = cherrypy.tree.apps[sn] method = req.method path = req.uri qs = req.args or "" sproto = req.protocol headers = req.headers_in.items() rfile = _ReadOnlyRequest(req) prev = None redirections = [] while True: request = cherrypy.engine.request(local, remote, scheme) request.login = req.user request.multithread = bool(threaded) request.multiprocess = bool(forked) request.app = app request.prev = prev # Run the CherryPy Request object and obtain the response try: response = request.run(method, path, qs, sproto, headers, rfile) break except cherrypy.InternalRedirect, ir: cherrypy.engine.release() prev = request if not recursive: if ir.path in redirections: raise RuntimeError("InternalRedirector visited the " "same URL twice: %r" % ir.path) else: # Add the *previous* path_info + qs to redirections. if qs: qs = "?" + qs redirections.append(sn + path + qs) # Munge environment and try again. method = "GET" path = ir.path qs = ir.query_string rfile = StringIO.StringIO() send_response(req, response.status, response.header_list, response.body) cherrypy.engine.release() except: tb = format_exc() cherrypy.log(tb) s, h, b = bare_error() send_response(req, s, h, b) return apache.OK
def log_traceback(): """Write the last error's traceback to the cherrypy error log.""" from cherrypy import _cperror cherrypy.log(_cperror.format_exc(), "HTTP")
def handler(req): from mod_python import apache try: global _isSetUp if not _isSetUp: setup(req) _isSetUp = True # Obtain a Request object from CherryPy local = req.connection.local_addr local = httputil.Host( local[0], local[1], req.connection.local_host or '') remote = req.connection.remote_addr remote = httputil.Host( remote[0], remote[1], req.connection.remote_host or '') scheme = req.parsed_uri[0] or 'http' req.get_basic_auth_pw() try: # apache.mpm_query only became available in mod_python 3.1 q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: bad_value = ("You must provide a PythonOption '%s', " "either 'on' or 'off', when running a version " 'of mod_python < 3.1') options = req.get_options() threaded = options.get('multithread', '').lower() if threaded == 'on': threaded = True elif threaded == 'off': threaded = False else: raise ValueError(bad_value % 'multithread') forked = options.get('multiprocess', '').lower() if forked == 'on': forked = True elif forked == 'off': forked = False else: raise ValueError(bad_value % 'multiprocess') sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: send_response(req, '404 Not Found', [], '') else: app = cherrypy.tree.apps[sn] method = req.method path = req.uri qs = req.args or '' reqproto = req.protocol headers = copyitems(req.headers_in) rfile = _ReadOnlyRequest(req) prev = None try: redirections = [] while True: request, response = app.get_serving(local, remote, scheme, 'HTTP/1.1') request.login = req.user request.multithread = bool(threaded) request.multiprocess = bool(forked) request.app = app request.prev = prev # Run the CherryPy Request object and obtain the response try: request.run(method, path, qs, reqproto, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not recursive: if ir.path in redirections: raise RuntimeError( 'InternalRedirector visited the same URL ' 'twice: %r' % ir.path) else: # Add the *previous* path_info + qs to # redirections. if qs: qs = '?' + qs redirections.append(sn + path + qs) # Munge environment and try again. method = 'GET' path = ir.path qs = ir.query_string rfile = io.BytesIO() send_response( req, response.output_status, response.header_list, response.body, response.stream) finally: app.release_serving() except: tb = format_exc() cherrypy.log(tb, 'MOD_PYTHON', severity=logging.ERROR) s, h, b = bare_error() send_response(req, s, h, b) return apache.OK
def log_traceback(): """Write the last error's traceback to the cherrypy error log.""" from cherrypy import _cperror cherrypy.log(_cperror.format_exc(), "HTTP")
def handle_error(): cherrypy.response.status = 500 tmpl = lookup.get_template("error.mako") details=_cperror.format_exc().replace("\n","<br/>") return tmpl.render(details=details)
qs = "?" + qs redirections.append(sn + path + qs) # Munge environment and try again. method = "GET" path = ir.path qs = ir.query_string rfile = StringIO() self.send_response( response.output_status, response.header_list, response.body) finally: app.release_serving() except: tb = format_exc() #print tb cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b) def send_response(self, status, headers, body): req = self.req # Set response status req.status = str(status or "500 Server Error") # Set response headers for header, value in headers: req.outheaders.append((header, value)) if (req.ready and not req.sent_headers):
def respond(self): req = self.req try: # Obtain a Request object from CherryPy local = req.server.bind_addr local = httputil.Host(local[0], local[1], "") remote = req.conn.remote_addr, req.conn.remote_port remote = httputil.Host(remote[0], remote[1], "") scheme = req.scheme sn = cherrypy.tree.script_name(req.uri or "/") if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = req.method path = req.path qs = req.qs or "" headers = list(req.inheaders.items()) rfile = req.rfile prev = None try: redirections = [] while True: request, response = app.get_serving( local, remote, scheme, "HTTP/1.1") request.multithread = True request.multiprocess = False request.app = app request.prev = prev # Run the CherryPy Request object and obtain the response try: request.run(method, path, qs, req.request_protocol, headers, rfile) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1] app.release_serving() prev = request if not self.recursive: if ir.path in redirections: raise RuntimeError( "InternalRedirector visited the " "same URL twice: %r" % ir.path) else: # Add the *previous* path_info + qs to redirections. if qs: qs = "?" + qs redirections.append(sn + path + qs) # Munge environment and try again. method = "GET" path = ir.path qs = ir.query_string rfile = BytesIO() self.send_response(response.output_status, response.header_list, response.body) finally: app.release_serving() except: tb = format_exc() #print tb cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b)