📄 publisher.py
字号:
# # Copyright 2004 Apache Software Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # # Originally developed by Gregory Trubetskoy. # # $Id: publisher.py 468839 2006-10-29 07:07:21Z grahamd $""" This handler is conceptually similar to Zope's ZPublisher, except that it: 1. Is written specifically for mod_python and is therefore much faster 2. Does not require objects to have a documentation string 3. Passes all arguments as simply string 4. Does not try to match Python errors to HTTP errors 5. Does not give special meaning to '.' and '..'."""import apacheimport utilimport sysimport osfrom os.path import exists, isabs, normpath, split, isfile, join, dirnameimport impimport reimport base64import newimport typesfrom types import *imp_suffixes = " ".join([x[0][1:] for x in imp.get_suffixes()])####################### The published page cache ##############################from cache import ModuleCache, NOT_INITIALIZEDclass PageCache(ModuleCache): """ This is the cache for page objects. Handles the automatic reloading of pages. """ def key(self, req): """ Extracts the normalized filename from the request """ return req.filename def check(self, key, req, entry): config = req.get_config() autoreload=int(config.get("PythonAutoReload", 1)) if autoreload==0 and entry._value is not NOT_INITIALIZED: # if we don't want to reload and we have a value, # then we consider it fresh return None else: return ModuleCache.check(self, key, req, entry) def build(self, key, req, opened, entry): config = req.get_config() log=int(config.get("PythonDebug", 0)) if log: if entry._value is NOT_INITIALIZED: req.log_error('Publisher loading page %s'%req.filename, apache.APLOG_NOTICE) else: req.log_error('Publisher reloading page %s'%req.filename, apache.APLOG_NOTICE) return ModuleCache.build(self, key, req, opened, entry)page_cache = PageCache()####################### Interface to the published page cache ################## # def get_page(req, path):# """# This imports a published page. If the path is absolute it is used as is.# If it is a relative path it is relative to the published page# where the request is really handled (not relative to the path# given in the URL).# # Warning : in order to maintain consistency in case of module reloading,# do not store the resulting module in a place that outlives the request# duration.# """# # real_filename = req.filename# # try:# if isabs(path):# req.filename = path# else:# req.filename = normpath(join(dirname(req.filename), path))# # return page_cache[req]# # finally:# req.filename = real_filename####################### The publisher handler himself ########################## def handler(req): req.allow_methods(["GET", "POST", "HEAD"]) if req.method not in ["GET", "POST", "HEAD"]: raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED # Derive the name of the actual module which will be # loaded. In older version of mod_python.publisher # you can't actually have a code file name which has # an embedded '.' in it except for that used by the # extension. This is because the standard Python # module import system which is used will think that # you are importing a submodule of a package. In # this code, because the standard Python module # import system isn't used and the actual file is # opened directly by name, an embedded '.' besides # that used for the extension will technically work. path,module_name = os.path.split(req.filename) # If the request is against a directory, fallback to # looking for the 'index' module. This is determined # by virtue of the fact that Apache will always add # a trailing slash to 'req.filename' when it matches # a directory. This will mean that the calculated # module name will be empty. if not module_name: module_name = 'index' # Now need to strip off any special extension which # was used to trigger this handler in the first place. suffixes = ['py'] suffixes += req.get_addhandler_exts().split() if req.extension: suffixes.append(req.extension[1:]) exp = '\\.' + '$|\\.'.join(suffixes) + '$' suff_matcher = re.compile(exp) module_name = suff_matcher.sub('',module_name) # Next need to determine the path for the function # which will be called from 'req.path_info'. The # leading slash and possibly any trailing slash are # eliminated. There would normally be at most one # trailing slash as Apache eliminates duplicates # from the original URI. func_path = '' if req.path_info: func_path = req.path_info[1:] if func_path[-1:] == '/': func_path = func_path[:-1] # Now determine the actual Python module code file # to load. This will first try looking for the file # '/path/<module_name>.py'. If this doesn't exist, # will try fallback of using the 'index' module, # ie., look for '/path/index.py'. In doing this, the # 'func_path' gets adjusted so the lead part is what # 'module_name' was set to. req.filename = path + '/' + module_name + '.py' if not exists(req.filename): if func_path: func_path = module_name + '/' + func_path else: func_path = module_name module_name = 'index' req.filename = path + '/' + module_name + '.py' if not exists(req.filename): raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND # Default to looking for the 'index' function if no # function path definition was supplied. if not func_path: func_path = 'index' # Turn slashes into dots. func_path = func_path.replace('/', '.') # Normalise req.filename to avoid Win32 issues. req.filename = normpath(req.filename) # We use the page cache to load the module module = page_cache[req] # does it have an __auth__? realm, user, passwd = process_auth(req, module) # resolve the object ('traverse') object = resolve_object(req, module, func_path, realm, user, passwd) # publish the object published = publish_object(req, object) # we log a message if nothing was published, it helps with debugging if (not published) and (req._bytes_queued==0) and (req.next is None): log=int(req.get_config().get("PythonDebug", 0)) if log: req.log_error("mod_python.publisher: nothing to publish.") return apache.OKdef process_auth(req, object, realm="unknown", user=None, passwd=None): found_auth, found_access = 0, 0 if hasattr(object, "__auth_realm__"): realm = object.__auth_realm__ func_object = None if type(object) is FunctionType: func_object = object elif type(object) == types.MethodType: func_object = object.im_func if func_object: # functions are a bit tricky func_code = func_object.func_code func_globals = func_object.func_globals def lookup(name): i = None if name in func_code.co_names: i = list(func_code.co_names).index(name)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -