📄 apache.py
字号:
# result. if len(value.args) == 2: (result, status) = value.args if status: req.status = status else: result = value.args[0] assert (type(result) == types.IntType), \ _result_warning % type(result) # stop cycling through handlers if result not in expected: break elif hlist.silent: # A missing handler when in silent mode will # only propagate DECLINED if it is the first # and only handler. if result == HTTP_INTERNAL_SERVER_ERROR: result = DECLINED hlist.next() except PROG_TRACEBACK, traceblock: # Program run-time error try: (etype, value, traceback) = traceblock result = self.ReportError(etype, value, traceback, req=req, phase=req.phase, hname=hlist.handler, debug=debug) finally: traceback = None except: # Any other rerror (usually parsing) try: exc_type, exc_value, exc_traceback = sys.exc_info() result = self.ReportError(exc_type, exc_value, exc_traceback, req=req, phase=req.phase, hname=hlist.handler, debug=debug) finally: exc_traceback = None return result def IncludeDispatch(self, filter, tag, code): try: config = filter.req.get_config() debug = int(config.get("PythonDebug", 0)) if not hasattr(filter.req,"ssi_globals"): filter.req.ssi_globals = {} filter.req.ssi_globals["filter"] = filter filter.req.ssi_globals["__file__"] = filter.req.filename code = code.replace('\r\n', '\n').rstrip() if tag == 'eval': result = eval(code, filter.req.ssi_globals) if result is not None: filter.write(str(result)) elif tag == 'exec': exec(code, filter.req.ssi_globals) filter.flush() except: try: exc_type, exc_value, exc_traceback = sys.exc_info() result = self.ReportError(exc_type, exc_value, exc_traceback, filter=filter, phase=filter.name, hname=filter.req.filename, debug=debug) finally: exc_traceback = None raise filter.req.ssi_globals["filter"] = None return OK def ImportDispatch(self, name): config = main_server.get_config() debug = int(config.get("PythonDebug", "0")) # evaluate pythonpath and set sys.path to # resulting value if not already done if config.has_key("PythonPath"): _path_cache_lock.acquire() try: pathstring = config["PythonPath"] if not _path_cache.has_key(pathstring): newpath = eval(pathstring) _path_cache[pathstring] = None sys.path[:] = newpath finally: _path_cache_lock.release() # split module::function l = name.split('::', 1) module_name = l[0] func_name = None if len(l) != 1: func_name = l[1] module = import_module(module_name, log=debug) if func_name: getattr(module, func_name)() def ReportError(self, etype, evalue, etb, req=None, filter=None, srv=None, phase="N/A", hname="N/A", debug=0): """ This function is only used when debugging is on. It sends the output similar to what you'd see when using Python interactively to the browser """ try: # try/finally try: # try/except if str(etype) == "exceptions.IOError" \ and str(evalue)[:5] == "Write": # if this is an IOError while writing to client, # it is probably better not to try to write to the cleint # even if debug is on. debug = 0 # write to log for e in traceback.format_exception(etype, evalue, etb): s = "%s %s: %s" % (phase, hname, e[:-1]) if req: req.log_error(s, APLOG_NOERRNO|APLOG_ERR) else: _apache.log_error(s, APLOG_NOERRNO|APLOG_ERR, srv) if not debug or not req: return HTTP_INTERNAL_SERVER_ERROR else: # write to client req.status = HTTP_INTERNAL_SERVER_ERROR req.content_type = 'text/html' s = '\n<pre>\nMod_python error: "%s %s"\n\n' % (phase, hname) for e in traceback.format_exception(etype, evalue, etb): s = s + cgi.escape(e) + '\n' s = s + "</pre>\n" if filter: filter.write(s) filter.flush() else: req.write(s) return DONE except: # last try traceback.print_exc() sys.stderr.flush() finally: # erase the traceback etb = None # we do not return anythingdef import_module(module_name, autoreload=1, log=0, path=None): """ Get the module to handle the request. If autoreload is on, then the module will be reloaded if it has changed since the last import. """ # nlehuen: this is a big lock, we'll have to refine it later to get better performance. # For now, we'll concentrate on thread-safety. imp.acquire_lock() try: # (Re)import if sys.modules.has_key(module_name): # The module has been imported already module = sys.modules[module_name] # but is it in the path? file = module.__dict__.get("__file__") # the "and not" part of this condition is to prevent execution # of arbitrary already imported modules, such as os. The # reason we use startswith as opposed to exact match is that # modules inside packages are actually in subdirectories. if not file or (path and not filter(file.startswith, path)): # there is a script by this name already imported, but it's in # a different directory, therefore it's a different script mtime, oldmtime = 0, -1 elif autoreload: oldmtime = module.__dict__.get("__mtime__", 0) mtime = module_mtime(module) else: mtime, oldmtime = 0, 0 else: mtime, oldmtime = 0, -1 if mtime != oldmtime: # Import the module if log: if path: s = "mod_python: (Re)importing module '%s' with path set to '%s'" % (module_name, path) else: s = "mod_python: (Re)importing module '%s'" % module_name _apache.log_error(s, APLOG_NOERRNO|APLOG_NOTICE) parent = None parts = module_name.split('.') for i in range(len(parts)): f, p, d = imp.find_module(parts[i], path) try: mname = ".".join(parts[:i+1]) module = imp.load_module(mname, f, p, d) if parent: setattr(parent,parts[i],module) parent = module finally: if f: f.close() if hasattr(module, "__path__"): path = module.__path__ if mtime == 0: mtime = module_mtime(module) module.__mtime__ = mtime return module finally: imp.release_lock()def module_mtime(module): """Get modification time of module""" mtime = 0 if module.__dict__.has_key("__file__"): filepath = module.__file__ try: # this try/except block is a workaround for a Python bug in # 2.0, 2.1 and 2.1.1. See # http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=422004 if os.path.exists(filepath): mtime = os.path.getmtime(filepath) if os.path.exists(filepath[:-1]) : mtime = max(mtime, os.path.getmtime(filepath[:-1])) except OSError: pass return mtimedef resolve_object(module, object_str, arg=None, silent=0): """ This function traverses the objects separated by . (period) to find the last one we're looking for: From left to right, find objects, if it is an unbound method of a class, instantiate the class passing the request as single argument 'arg' is sometimes req, sometimes filter, sometimes connection """ obj = module for obj_str in object_str.split('.'): parent = obj # don't throw attribute errors when silent if silent and not hasattr(obj, obj_str): return None # this adds a little clarity if we have an attriute error if obj == module and not hasattr(module, obj_str): if hasattr(module, "__file__"): s = "module '%s' contains no '%s'" % (module.__file__, obj_str) raise AttributeError, s obj = getattr(obj, obj_str) if hasattr(obj, "im_self") and not obj.im_self: # this is an unbound method, its class # needs to be instantiated instance = parent(arg) obj = getattr(instance, obj_str) return objdef build_cgi_env(req): """ Utility function that returns a dictionary of CGI environment variables as described in http://hoohoo.ncsa.uiuc.edu/cgi/env.html """ req.add_common_vars() env = req.subprocess_env.copy() if req.path_info and len(req.path_info) > 0: env["SCRIPT_NAME"] = req.uri[:-len(req.path_info)] else: env["SCRIPT_NAME"] = req.uri env["GATEWAY_INTERFACE"] = "Python-CGI/1.1" # you may want to comment this out for better security if req.headers_in.has_key("authorization"): env["HTTP_AUTHORIZATION"] = req.headers_in["authorization"] return envclass NullIO: """ Abstract IO """ def tell(self): return 0 def read(self, n = -1): return "" def readline(self, length = None): return "" def readlines(self): return [] def write(self, s): pass def writelines(self, list): self.write("".join(list)) def isatty(self): return 0 def flush(self): pass def close(self): pass def seek(self, pos, mode = 0): passclass CGIStdin(NullIO): def __init__(self, req): self.pos = 0 self.req = req self.BLOCK = 65536 # 64K # note that self.buf sometimes contains leftovers # that were read, but not used when readline was used self.buf = "" def read(self, n = -1): if n == 0: return "" if n == -1: s = self.req.read(self.BLOCK) while s: self.buf = self.buf + s self.pos = self.pos + len(s) s = self.req.read(self.BLOCK) result = self.buf self.buf = "" return result else: if self.buf: s = self.buf[:n] n = n - len(s) else: s = "" s = s + self.req.read(n) self.pos = self.pos + len(s) return s def readlines(self): s = (self.buf + self.read()).split('\n') return map(lambda s: s + '\n', s) def readline(self, n = -1): if n == 0: return "" # fill up the buffer self.buf = self.buf + self.req.read(self.BLOCK) # look for \n in the buffer i = self.buf.find('\n') while i == -1: # if \n not found - read more if (n != -1) and (len(self.buf) >= n): # we're past n i = n - 1 break x = len(self.buf) self.buf = self.buf + self.req.read(self.BLOCK) if len(self.buf) == x: # nothing read, eof i = x - 1 break i = self.buf.find('\n', x)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -