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 next(self): try: chunk = self.iter_response.next() # WSGI requires all data to be of type "str". This coercion should # not take any time at all if chunk is already of type "str". # If it's unicode, it could be a big performance hit (x ~500). if not isinstance(chunk, str): chunk = chunk.encode("ISO-8859-1") return chunk except self.throws: raise except StopIteration: raise except: if getattr(self.request, "throw_errors", False): raise _cherrypy.log(traceback=True) # 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([]) return "".join(b)
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 ntob("").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 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 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 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 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 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 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 run(self, method, path, query_string, req_protocol, headers, rfile): """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. They both MUST be byte strings, not unicode strings. 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 = {} 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): 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 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
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) self.close() raise
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 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 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 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 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)
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) self.close() raise
# 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): req.sent_headers = True req.send_headers()
def respond(self): """Obtain response from CherryPy machinery and then send it.""" req = self.req try: # Obtain a Request object from CherryPy local = req.server.bind_addr # FIXME: handle UNIX sockets local = tonative(local[0]), local[1] local = httputil.Host(local[0], local[1], '') remote = tonative(req.conn.remote_addr), req.conn.remote_port remote = httputil.Host(remote[0], remote[1], '') scheme = tonative(req.scheme) sn = cherrypy.tree.script_name(tonative(req.uri or '/')) if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = tonative(req.method) path = tonative(req.path) qs = tonative(req.qs or '') headers = ((tonative(h), tonative(v)) for h, v in 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, tonative(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 Exception: tb = format_exc() # print tb cherrypy.log(tb, 'NATIVE_ADAPTER', severity=logging.ERROR) s, h, b = bare_error() self.send_response(s, h, b)