def __init__(self, req, options): environ = {} environ.update(apache.build_cgi_env(req)) environ['trac.web.frontend'] = 'mod_python' environ['trac.web.version'] = version if 'TracEnv' in options: environ['trac.env_path'] = options['TracEnv'] if 'TracEnvParentDir' in options: environ['trac.env_parent_dir'] = options['TracEnvParentDir'] if 'TracEnvIndexTemplate' in options: environ['trac.env_index_template'] = options['TracEnvIndexTemplate'] if 'TracTemplateVars' in options: environ['trac.template_vars'] = options['TracTemplateVars'] if 'TracLocale' in options: environ['trac.locale'] = options['TracLocale'] if 'TracUriRoot' in options: # Special handling of SCRIPT_NAME/PATH_INFO for mod_python, which # tends to get confused for whatever reason root_uri = options['TracUriRoot'].rstrip('/') request_uri = environ['REQUEST_URI'].split('?', 1)[0] if not request_uri.startswith(root_uri): raise ValueError('TracUriRoot set to %s but request URL ' 'is %s' % (root_uri, request_uri)) environ['SCRIPT_NAME'] = root_uri environ['PATH_INFO'] = urllib.unquote(request_uri[len(root_uri):]) WSGIGateway.__init__(self, environ, InputWrapper(req), _ErrorsWrapper(lambda x: req.log_error(x))) self.req = req
def __init__(self, req, options): environ = {} environ.update(apache.build_cgi_env(req)) environ['trac.web.frontend'] = 'mod_python' environ['trac.web.version'] = version if 'TracEnv' in options: environ['trac.env_path'] = options['TracEnv'] if 'TracEnvParentDir' in options: environ['trac.env_parent_dir'] = options['TracEnvParentDir'] if 'TracEnvIndexTemplate' in options: environ['trac.env_index_template'] = options[ 'TracEnvIndexTemplate'] if 'TracTemplateVars' in options: environ['trac.template_vars'] = options['TracTemplateVars'] if 'TracLocale' in options: environ['trac.locale'] = options['TracLocale'] if 'TracUriRoot' in options: # Special handling of SCRIPT_NAME/PATH_INFO for mod_python, which # tends to get confused for whatever reason root_uri = options['TracUriRoot'].rstrip('/') request_uri = environ['REQUEST_URI'].split('?', 1)[0] if not request_uri.startswith(root_uri): raise ValueError('TracUriRoot set to %s but request URL ' 'is %s' % (root_uri, request_uri)) environ['SCRIPT_NAME'] = root_uri environ['PATH_INFO'] = urllib.unquote(request_uri[len(root_uri):]) WSGIGateway.__init__(self, environ, InputWrapper(req), _ErrorsWrapper(lambda x: req.log_error(x))) self.req = req
def pspHandler(self, req): self.reset(req) try: # Get input myInput = self.input(req) # get the apache module to do the grunt work of # building the environment env = apache.build_cgi_env(req) #make sure env is a dictionary (may not be for Apache2) env = dict(env) # Special environment setup needed for psp handler env['WK_ABSOLUTE'] = '1' # Fix up the path if 'PATH_INFO' not in env: env['PATH_INFO'] = req.path_info # Communicate with the app server respdict = self.transactWithAppServer(env, myInput, self.host, self.port) # Respond back to Apache self.respond(req, respdict) except: self.handleException(req) return apache.OK
def pspHandler(self, req): self.reset(req) try: # Get input myInput = self.input(req) # get the apache module to do the grunt work of # building the environment env = apache.build_cgi_env(req) # make sure env is a dictionary (may not be for Apache2) env = dict(env) # Special environment setup needed for psp handler env['WK_ABSOLUTE'] = '1' # Fix up the path if 'PATH_INFO' not in env: env['PATH_INFO'] = req.path_info # Communicate with the app server self.transactWithAppServer(env, myInput, self.host, self.port) except Exception: self.handleException(req) return apache.OK
def handler(self, req): self.reset(req) try: # Get input myInput = self.input(req) # get the apache module to do the grunt work of # building the environment env=apache.build_cgi_env(req) #make sure env is a dictionary (may not be for Apache2) env=dict(env) # Fix up the path if not env.has_key('PATH_INFO'): env['PATH_INFO']=req.path_info # Communicate with the app server respdict = self.transactWithAppServer(env, myInput, self.host, self.port) # Respond back to Apache #self.respond(req, respdict) except: self.handleException(req) return apache.OK
def run(publisher, req): response = publisher.process(apache.CGIStdin(req), apache.build_cgi_env(req)) try: response.write(apache.CGIStdout(req)) except IOError, err: publisher.log("IOError while sending response ignored: %s" % err)
def run(publisher, req): response = publisher.process(apache.CGIStdin(req), apache.build_cgi_env(req)) try: response.write(apache.CGIStdout(req)) except IOError, err: publisher.log("IOError while sending response ignored: %s" % err)
def handler(req): env = apache.build_cgi_env(req) if os.path.exists("/etc/ros/env"): keys = os.listdir("/etc/ros/env/") for key in keys: if key not in os.environ: os.environ[key] = open("/etc/ros/env/%s" % key).read().strip() ros_root = os.environ['ROS_ROOT'] roslib_src = os.path.join(ros_root, "core/roslib/src") if not roslib_src in sys.path: sys.path.append(roslib_src) if os.environ['PATH'].find(ros_root) == -1: os.environ['PATH'] = os.path.join(ros_root, 'bin') + ":" + os.environ.get('PATH', '') os.environ['HOME'] = '/tmp' os.environ['ROS_CACHE_TIMEOUT'] = '3600' if env.get('PYTHON_RELOADER', '').lower() == 'on': from pyclearsilver import autoreloader import cgistarter import config #sys.stderr.write("path:" + os.getcwd()) path,f = os.path.split(__file__) #sys.stderr.write("path: %s\n" % path) cwd = path #os.chdir(path) cgistarter.setConfig(config) return cgistarter.handler(req, cwd)
def __init__(self, req, options): environ = {} environ.update(apache.build_cgi_env(req)) environ["trac.web.frontend"] = "mod_python" environ["trac.web.version"] = version if "TracEnv" in options: environ["trac.env_path"] = options["TracEnv"] if "TracEnvParentDir" in options: environ["trac.env_parent_dir"] = options["TracEnvParentDir"] if "TracEnvIndexTemplate" in options: environ["trac.env_index_template"] = options["TracEnvIndexTemplate"] if "TracTemplateVars" in options: environ["trac.template_vars"] = options["TracTemplateVars"] if "TracLocale" in options: environ["trac.locale"] = options["TracLocale"] if "TracUriRoot" in options: # Special handling of SCRIPT_NAME/PATH_INFO for mod_python, which # tends to get confused for whatever reason root_uri = options["TracUriRoot"].rstrip("/") request_uri = environ["REQUEST_URI"].split("?", 1)[0] if not request_uri.startswith(root_uri): raise ValueError("TracUriRoot set to %s but request URL " "is %s" % (root_uri, request_uri)) environ["SCRIPT_NAME"] = root_uri environ["PATH_INFO"] = urllib.unquote(request_uri[len(root_uri) :]) WSGIGateway.__init__(self, environ, InputWrapper(req), _ErrorsWrapper(lambda x: req.log_error(x))) self.req = req
def handler(self, req): self.reset(req) try: # Get input myInput = self.input(req) # get the apache module to do the grunt work of # building the environment env = apache.build_cgi_env(req) #make sure env is a dictionary (may not be for Apache2) env = dict(env) # Fix up the path if not env.has_key('PATH_INFO'): env['PATH_INFO'] = req.path_info # Communicate with the app server respdict = self.transactWithAppServer(env, myInput, self.host, self.port) # Respond back to Apache #self.respond(req, respdict) except: self.handleException(req) return apache.OK
def __init__(self, req, options): environ = {} environ.update(apache.build_cgi_env(req)) environ['mod_python.options'] = options environ['mod_python.subprocess_env'] = req.subprocess_env WSGIGateway.__init__(self, environ, InputWrapper(req), _ErrorsWrapper(lambda x: req.log_error(x))) self.req = req
def __init__(self, req, options): environ = {} environ.update(apache.build_cgi_env(req)) environ['mod_python.options'] = options environ['mod_python.subprocess_env'] = req.subprocess_env WSGIGateway.__init__(self, environ, InputWrapper(req), _ErrorsWrapper(lambda x: req.log_error(x))) self.req = req
def run(publisher, req): from quixote.http_request import HTTPRequest request = HTTPRequest(apache.CGIStdin(req), apache.build_cgi_env(req)) response = publisher.process_request(request) try: response.write(apache.CGIStdout(req)) except IOError, err: publisher.log("IOError while sending response ignored: %s" % err)
def run(publisher, req): from quixote.http_request import HTTPRequest request = HTTPRequest(apache.CGIStdin(req), apache.build_cgi_env(req)) response = publisher.process_request(request) try: response.write(apache.CGIStdout(req)) except IOError, err: publisher.log("IOError while sending response ignored: %s" % err)
def __init__(self, request, **kwargs): from mod_python import apache, Cookie from mod_python.util import FieldStorage Request.__init__(self, **kwargs) self.cookie_mod = Cookie self.request = request self.env = apache.build_cgi_env(request) self.the_get_data = self.__read_get_data() self.the_post_data = self.__read_post_data() self.the_cookies = self.__read_cookies()
def publish_modpython(self, req): """publish_modpython() -> None Entry point from mod_python. """ self.__apache_request = req try: self.publish(apache.CGIStdin(req), apache.CGIStdout(req), sys.stderr, apache.build_cgi_env(req)) return apache.OK finally: self.__apache_request = None
def __init__(self, req): """ Handler constructor """ self.started = False options = req.get_options() # Threading and forking try: q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: 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') env = self.environ = dict(apache.build_cgi_env(req)) if 'SCRIPT_NAME' in options: # Override SCRIPT_NAME and PATH_INFO if requested. env['SCRIPT_NAME'] = options['SCRIPT_NAME'] env['PATH_INFO'] = req.uri[len(options['SCRIPT_NAME']):] env['wsgi.input'] = InputWrapper(req) env['wsgi.errors'] = ErrorWrapper(req) env['wsgi.version'] = (1, 0) env['wsgi.run_once'] = False if env.get('HTTPS') in ('yes', 'on', '1'): env['wsgi.url_scheme'] = 'https' else: env['wsgi.url_scheme'] = 'http' env['wsgi.multithread'] = threaded env['wsgi.multiprocess'] = forked self.request = req
def __init__(self, req): """ Handler constructor """ self.started = False options = req.get_options() # Threading and forking try: q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: 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') env = self.environ = dict(apache.build_cgi_env(req)) if 'SCRIPT_NAME' in options: # Override SCRIPT_NAME and PATH_INFO if requested. env['SCRIPT_NAME'] = options['SCRIPT_NAME'] env['PATH_INFO'] = req.uri[len(options['SCRIPT_NAME']):] env['wsgi.input'] = InputWrapper(req) env['wsgi.errors'] = ErrorWrapper(req) env['wsgi.version'] = (1, 0) env['wsgi.run_once'] = False if env.get('HTTPS') in ('yes', 'on', '1'): env['wsgi.url_scheme'] = 'https' else: env['wsgi.url_scheme'] = 'http' env['wsgi.multithread'] = threaded env['wsgi.multiprocess'] = forked self.request = req
def __init__(self, req): self.started = False options = req.get_options() # Threading and forking try: q = apache.mpm_query threaded = q(apache.AP_MPMQ_IS_THREADED) forked = q(apache.AP_MPMQ_IS_FORKED) except AttributeError: 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") env = self.environ = dict(apache.build_cgi_env(req)) if "SCRIPT_NAME" in options: # Override SCRIPT_NAME and PATH_INFO if requested. env["SCRIPT_NAME"] = options["SCRIPT_NAME"] env["PATH_INFO"] = req.uri[len(options["SCRIPT_NAME"]) :] else: env["SCRIPT_NAME"] = "" env["PATH_INFO"] = req.uri env["wsgi.input"] = InputWrapper(req) env["wsgi.errors"] = ErrorWrapper(req) env["wsgi.version"] = (1, 0) env["wsgi.run_once"] = False if env.get("HTTPS") in ("yes", "on", "1"): env["wsgi.url_scheme"] = "https" else: env["wsgi.url_scheme"] = "http" env["wsgi.multithread"] = threaded env["wsgi.multiprocess"] = forked self.request = req
def publish_modpython(self, req): """publish_modpython() -> None Entry point from mod_python. """ self.__apache_request = req try: self.publish(apache.CGIStdin(req), apache.CGIStdout(req), sys.stderr, apache.build_cgi_env(req)) return apache.OK finally: self.__apache_request = None
def __init__(self, req): from mod_python import apache self.stdout = apache.CGIStdout(req) self.stdin = apache.CGIStdin(req) self.stderr = FakeError() env = apache.build_cgi_env(req) self.environ = env scriptFilename = self.environ.get("SCRIPT_FILENAME", "") if scriptFilename: path, fn = os.path.split(scriptFilename) os.chdir(path)
def __init__ (self, req): from mod_python import apache self.stdout = apache.CGIStdout(req) self.stdin = apache.CGIStdin(req) self.stderr = FakeError() env = apache.build_cgi_env(req) self.environ = env scriptFilename = self.environ.get("SCRIPT_FILENAME", "") if scriptFilename: path, fn = os.path.split(scriptFilename) os.chdir(path)
def handler(req): env = apache.build_cgi_env(req) if os.path.exists("/etc/ros/env"): keys = os.listdir("/etc/ros/env/") for key in keys: if key not in os.environ: os.environ[key] = open("/etc/ros/env/%s" % key).read().strip() ros_root = os.environ['ROS_ROOT'] roslib_src = os.path.join(ros_root, "core/roslib/src") if not roslib_src in sys.path: sys.path.append(roslib_src) if os.environ['PATH'].find(ros_root) == -1: os.environ['PATH'] = os.path.join( ros_root, 'bin') + ":" + os.environ.get('PATH', '') os.environ['HOME'] = '/tmp' os.environ['ROS_CACHE_TIMEOUT'] = '3600' if env.get('PYTHON_RELOADER', '').lower() == 'on': from pyclearsilver import autoreloader import cgistarter import config #sys.stderr.write("path:" + os.getcwd()) path, f = os.path.split(__file__) #sys.stderr.write("path: %s\n" % path) cwd = path #os.chdir(path) cgistarter.setConfig(config) return cgistarter.handler(req, cwd)
def handler(req): e=apache.build_cgi_env(req) #req.send_http_header() env = {} for bleh in e.keys(): env[bleh]=e[bleh] #print >> req, bleh, ":", e[bleh], "<br>" #return apache.OK wreq=weblib.Request(content=req.read(), environ=env) eng = ModPythonEngine(request=wreq,script="") eng.start() dir = os.sep.join(req.filename.split(os.sep)[:-1]) + os.sep os.chdir(dir) if os.path.exists(dir + ".weblib.py"): whichfile= dir + ".weblib.py" eng.execute(open(whichfile)) if (eng.result ==eng.SUCCESS) or (eng.result is None): whichfile=req.filename eng.execute(open(whichfile)) eng.stop() if eng.result in (eng.SUCCESS, eng.REDIRECT, eng.EXIT): import string headers = eng.response.getHeaders() for i in string.split(headers, "\n"): if i != "": header = string.split(i, ":") req.headers_out[header[0]] = header[1] if string.lower(header[0]) == 'content-type': req.content_type = header[1] if string.lower(header[0]) == 'status': req.status = int(header[1]) req.send_http_header() req.write(eng.response.buffer) return apache.OK else: ## print debug output print >> req, weblib.trim(""" <html> <head> <title>weblib.cgi exception</title> <style type="text/css"> body, p { background: #cccccc; font-family: verdana, arial; font-size: 75%; } pre { font-size: 120%; } pre.traceback { color: red; } pre.output{ color : green } </style> </head> <body> """) if eng.result == eng.FAILURE: print >> req, "<b>assertion failure:</b>", eng.error print >> req, "</body>\n</html>" elif eng.result == eng.EXCEPTION: ## html error message ################################# print >> req, "<b>uncaught exception while running %s</b><br>" \ % whichfile print >> req, '<pre class="traceback">' \ + weblib.htmlEncode(eng.error) + "</pre>" print >> req, "<b>script input:</b>" print >> req, '<ul>' print >> req, '<li>form: %s</li>' % eng.request.form print >> req, '<li>querystring: %s</li>' % eng.request.querystring print >> req, '<li>cookie: %s</li>' % eng.request.cookie print >> req, '</ul>' print >> req, '<b>session data:</b><br>' print >> req, '<ul>' for item in eng.sess.keys(): print >> req, '<li>', item, ': ' try: print >> req, eng.sess[item] except: print >> req, '(can\'t unpickle)' print >> req, '</li>' print >> req, '</ul>' print >> req, "<b>script output:</b>" print >> req, '<pre class="output">' + \ weblib.htmlEncode(eng.response.getHeaders()) + \ weblib.htmlEncode(eng.response.buffer) + \ "</pre>" print >> req, "<hr>" print >> req, '<a href="http://weblib.sourceforge.net/">weblib</a> ' + \ '(c) copyright 2000-2001 ' + \ '<a href="http://www.zike.net/">Zike Interactive</a>. ' + \ 'All rights reserved.' print >> req, "</body>" print >> req, "</html>" return apache.OK
def run(self, req): environ = dict(apache.build_cgi_env(req)) options = req.get_options() # we define those classes here to don't # give the user access to the mod python request # object using environ['wsgi.input']._req or # something similar. class InputStream(object): def close(self): pass def read(self, size=-1): return req.read(size) def readline(self): return req.readline() def readlines(self, hint=-1): return req.readlines(hint) def flush(self): pass def write(self, s): pass def writelines(self, seq): pass def __iter__(self): while True: line = self.readline() if not line: return yield line class ErrorStream(object): def read(self, size=-1): return '' def readline(self): return '\n' def readlines(self, hint=-1): return [] def flush(self): pass def write(self, s): req.log_error(s) def writelines(self, seq): for item in seq: req.log_error(item) def __iter__(self): return iter(int, 0) try: threaded = apache.mpm_query(apache.AP_MPMQ_IS_THREADED) forked = apache.mpm_query(apache.AP_MPMQ_IS_FORKED) except AttributeError: threaded = options.get('multithread', '').lower() == 'on' forked = options.get('multiprocess', '').lower() == 'on' if 'SCRIPT_NAME' in options: environ['SCRIPT_NAME'] = options['SCRIPT_NAME'] path_info = req.uri[len(options['SCRIPT_NAME']):] if path_info: environ['PATH_INFO'] = path_info if environ.get('HTTPS', '').lower() in ('1', 'yes', 'on'): url_scheme = 'https' else: url_scheme = 'http' environ.update({ 'wsgi.input': InputStream(), 'wsgi.error': ErrorStream(), 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': url_scheme, 'wsgi.multithread': threaded, 'wsgi.multiprocess': forked }) req.content_type = 'text/plain' headers_set = [] headers_sent = [] def write(data): if not headers_set: raise AssertionError('write() before start_response()') elif not headers_sent: status, response_headers = headers_sent[:] = headers_set req.status = int(status[:3]) for key, value in response_headers: if key.lower() == 'content-length': req.set_content_length(int(value)) elif key.lower() == 'content-type': req.content_type = value else: req.headers_out.add(key, value) req.write(data) def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif headers_set: raise AssertionError('Headers already set!') headers_set[:] = [status, response_headers] return write result = self._application(environ, start_response) try: for data in result: if data: write(data) if not headers_sent: write('') finally: if hasattr(result, 'close'): result.close() return apache.OK
def run(self, req): environ = dict(apache.build_cgi_env(req)) options = req.get_options() # we define those classes here to don't # give the user access to the mod python request # object using environ['wsgi.input']._req or # something similar. class InputStream(object): def close(self): pass def read(self, size=-1): return req.read(size) def readline(self): return req.readline() def readlines(self, hint=-1): return req.readlines(hint) def flush(self): pass def write(self, s): pass def writelines(self, seq): pass def __iter__(self): while True: line = self.readline() if not line: return yield line class ErrorStream(object): def read(self, size=-1): return '' def readline(self): return '\n' def readlines(self, hint=-1): return [] def flush(self): pass def write(self, s): req.log_error(s) def writelines(self, seq): for item in seq: req.log_error(item) def __iter__(self): return iter(int, 0) try: threaded = apache.mpm_query(apache.AP_MPMQ_IS_THREADED) forked = apache.mpm_query(apache.AP_MPMQ_IS_FORKED) except AttributeError: threaded = options.get('multithread', '').lower() == 'on' forked = options.get('multiprocess', '').lower() == 'on' # XXX: argh. a very stupid way for this problem but # mod_python otherwise does everything with our # SCRIPT_NAME/PATH_INFO but that what wsgi expects. # # the problem in short: # script installed on /a using .htaccess # # URI SCRIPT_NAME PATH_INFO # ---------------------------------------------------------------- # /a /a # /a/ /a / # /a/b /a/b # /a/b/ /a/b / # /a/b/c /a/b /c # /a/b/c/d /a/b /c/d # WTF???? #XXX: Is this right? if not options.get('untouched_scriptname', '').lower()\ in ('1', 'on', 'yes') and environ['SCRIPT_NAME']: path_info = None if 'PATH_TRANSLATED' in environ: try: _, script_name, prefix = environ['SCRIPT_NAME'].split('/', 2) except ValueError: script_name, prefix = environ['SCRIPT_NAME'].split('/', 2) script_name = '/' + script_name path_info = '/' + prefix + environ.get('PATH_INFO', '') elif 'PATH_INFO' not in environ: bits = environ['SCRIPT_NAME'].split('/') script_name = '/'.join(bits[:-1]) path_info = '/' + bits[-1] if script_name == '/': script_name = '' environ['SCRIPT_NAME'] = script_name if path_info: environ['PATH_INFO'] = path_info if environ.get('HTTPS', '').lower() in ('1', 'yes', 'on'): url_scheme = 'https' else: url_scheme = 'http' environ.update({ 'wsgi.input': InputStream(), 'wsgi.errors': ErrorStream(), 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': url_scheme, 'wsgi.multithread': threaded, 'wsgi.multiprocess': forked, }) req.content_type = 'text/plain' headers_set = [] headers_sent = [] def write(data): if not headers_set: raise AssertionError('write() before start_response()') elif not headers_sent: status, response_headers = headers_sent[:] = headers_set req.status = int(status[:3]) for key, value in response_headers: if key.lower() == 'content-length': req.set_content_length(int(value)) elif key.lower() == 'content-type': req.content_type = value else: req.headers_out.add(key, value) req.write(data) def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif headers_set: raise AssertionError('Headers already set!') headers_set[:] = [status, response_headers] return write result = self._application(environ, start_response) try: for data in result: if data: write(data) if not headers_sent: write('') finally: if hasattr(result, 'close'): result.close() return apache.OK
def handler(req): e = apache.build_cgi_env(req) #req.send_http_header() env = {} for bleh in e.keys(): env[bleh] = e[bleh] #print >> req, bleh, ":", e[bleh], "<br>" #return apache.OK wreq = weblib.Request(content=req.read(), environ=env) eng = ModPythonEngine(request=wreq, script="") eng.start() dir = os.sep.join(req.filename.split(os.sep)[:-1]) + os.sep os.chdir(dir) if os.path.exists(dir + ".weblib.py"): whichfile = dir + ".weblib.py" eng.execute(open(whichfile)) if (eng.result == eng.SUCCESS) or (eng.result is None): whichfile = req.filename eng.execute(open(whichfile)) eng.stop() if eng.result in (eng.SUCCESS, eng.REDIRECT, eng.EXIT): import string headers = eng.response.getHeaders() for i in string.split(headers, "\n"): if i != "": header = string.split(i, ":") req.headers_out[header[0]] = header[1] if string.lower(header[0]) == 'content-type': req.content_type = header[1] if string.lower(header[0]) == 'status': req.status = int(header[1]) req.send_http_header() req.write(eng.response.buffer) return apache.OK else: ## print debug output print >> req, weblib.trim(""" <html> <head> <title>weblib.cgi exception</title> <style type="text/css"> body, p { background: #cccccc; font-family: verdana, arial; font-size: 75%; } pre { font-size: 120%; } pre.traceback { color: red; } pre.output{ color : green } </style> </head> <body> """) if eng.result == eng.FAILURE: print >> req, "<b>assertion failure:</b>", eng.error print >> req, "</body>\n</html>" elif eng.result == eng.EXCEPTION: ## html error message ################################# print >> req, "<b>uncaught exception while running %s</b><br>" \ % whichfile print >> req, '<pre class="traceback">' \ + weblib.htmlEncode(eng.error) + "</pre>" print >> req, "<b>script input:</b>" print >> req, '<ul>' print >> req, '<li>form: %s</li>' % eng.request.form print >> req, '<li>querystring: %s</li>' % eng.request.querystring print >> req, '<li>cookie: %s</li>' % eng.request.cookie print >> req, '</ul>' print >> req, '<b>session data:</b><br>' print >> req, '<ul>' for item in eng.sess.keys(): print >> req, '<li>', item, ': ' try: print >> req, eng.sess[item] except: print >> req, '(can\'t unpickle)' print >> req, '</li>' print >> req, '</ul>' print >> req, "<b>script output:</b>" print >> req, '<pre class="output">' + \ weblib.htmlEncode(eng.response.getHeaders()) + \ weblib.htmlEncode(eng.response.buffer) + \ "</pre>" print >> req, "<hr>" print >> req, '<a href="http://weblib.sourceforge.net/">weblib</a> ' + \ '(c) copyright 2000-2001 ' + \ '<a href="http://www.zike.net/">Zike Interactive</a>. ' + \ 'All rights reserved.' print >> req, "</body>" print >> req, "</html>" return apache.OK
def run(self, req): environ = dict(apache.build_cgi_env(req)) options = req.get_options() # we define those classes here to don't # give the user access to the mod python request # object using environ['wsgi.input']._req or # something similar. class InputStream(object): def close(self): pass def read(self, size=-1): return req.read(size) def readline(self): return req.readline() def readlines(self, hint=-1): return req.readlines(hint) def flush(self): pass def write(self, s): pass def writelines(self, seq): pass def __iter__(self): while True: line = self.readline() if not line: return yield line class ErrorStream(object): def read(self, size=-1): return '' def readline(self): return '\n' def readlines(self, hint=-1): return [] def flush(self): pass def write(self, s): req.log_error(s) def writelines(self, seq): for item in seq: req.log_error(item) def __iter__(self): return iter(int, 0) try: threaded = apache.mpm_query(apache.AP_MPMQ_IS_THREADED) forked = apache.mpm_query(apache.AP_MPMQ_IS_FORKED) except AttributeError: threaded = options.get('multithread', '').lower() == 'on' forked = options.get('multiprocess', '').lower() == 'on' # XXX: argh. a very stupid way for this problem but # mod_python otherwise does everything with our # SCRIPT_NAME/PATH_INFO but that what wsgi expects. # the problem in short: # script installed on /a using .htaccess # # URI SCRIPT_NAME PATH_INFO # ---------------------------------------------------------------- # /a /a # /a/ /a / # /a/b /a/b # /a/b/ /a/b / # /a/b/c /a/b /c # /a/b/c/d /a/b /c/d # WTF???? if not options.get('untouched_scriptname', '').lower()\ in ('1', 'on', 'yes') and environ['SCRIPT_NAME']: # Then touch the scriptname path_info = None if 'PATH_TRANSLATED' in environ: try: _, script_name, prefix = environ['SCRIPT_NAME'].split( '/', 2) except ValueError: script_name, prefix = environ['SCRIPT_NAME'].split('/', 2) script_name = '/' + script_name path_info = '/' + prefix + environ.get('PATH_INFO', '') elif not 'PATH_INFO' in environ: bits = environ['SCRIPT_NAME'].split('/') script_name = '/'.join(bits[:-1]) path_info = '/' + bits[-1] if script_name == '/': script_name = '' environ['SCRIPT_NAME'] = script_name if path_info: environ['PATH_INFO'] = path_info if environ.get('HTTPS', '').lower() in ('1', 'yes', 'on'): url_scheme = 'https' else: url_scheme = 'http' environ.update({ 'wsgi.input': InputStream( ), # An input stream (file-like object) from which the HTTP request body can be read. 'wsgi.errors': ErrorStream(), # error log 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': url_scheme, 'wsgi.multithread': threaded, 'wsgi.multiprocess': forked, "options": options, # Note: Added this }) req.content_type = 'text/plain' headers_set = [] headers_sent = [] def write(data): if not headers_set: raise AssertionError('write() before start_response()') elif not headers_sent: status, response_headers = headers_sent[:] = headers_set req.status = int(status[:3]) for key, value in response_headers: if key.lower() == 'content-length': req.set_content_length(int(value)) elif key.lower() == 'content-type': req.content_type = value else: req.headers_out.add(key, value) req.write(data) def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif headers_set: raise AssertionError('Headers already set!') headers_set[:] = [status, response_headers] return write # Call the application result = self._application(environ, start_response) try: for data in result: if data: write(data) if not headers_sent: write('') finally: if hasattr(result, 'close'): result.close() return apache.OK