1 """WSGI handler for serving chained WSGI modules from physical files
3 The WSGI handler in this module examines the SCRIPT_FILENAME variable
4 of the requests it handles -- that is, the physical file corresponding
5 to the request, as determined by the webserver -- determining what to
6 do with the request based on the extension of that file.
8 By default, it handles files named `.wsgi' by compiling them into
9 Python modules and using them, in turn, as chained WSGI handlers, but
10 handlers for other extensions can be installed as well.
12 When handling `.wsgi' files, the compiled modules are cached and
13 reused until the file is modified, in which case the previous module
14 is discarded and the new file contents are loaded into a new module in
15 its place. When chaining such modules, an object named `wmain' is
16 first looked for and called with no arguments if found. The object it
17 returns is then used as the WSGI application object for that module,
18 which is reused until the module is reloaded. If `wmain' is not found,
19 an object named `application' is looked for instead. If found, it is
20 used directly as the WSGI application object.
22 This module itself contains both an `application' and a `wmain'
23 object. If this module is used by ashd-wsgi(1) or scgi-wsgi(1) so that
24 its wmain function is called, arguments can be specified to it to
25 install handlers for other file extensions. Such arguments take the
26 form `.EXT=MODULE.HANDLER', where EXT is the file extension to be
27 handled, and the MODULE.HANDLER string is treated by splitting it
28 along its last constituent dot. The part left of the dot is the name
29 of a module which is imported, and the part right of the dot is the
30 name of an object in that module, which should be a callable adhering
31 to the WSGI specification. When called, this module will have made
32 sure that the WSGI environment contains the SCRIPT_FILENAME parameter
33 and that it is properly working. For example, the argument
34 `.fpy=my.module.foohandler' can be given to pass requests for `.fpy'
35 files to the function `foohandler' in the module `my.module' (which
36 must, of course, be importable). When writing such handler functions,
37 you will probably want to use the getmod() function in this module.
40 import os, threading, types, importlib
41 from . import wsgiutil
43 __all__ = ["application", "wmain", "getmod", "cachedmod"]
45 class cachedmod(object):
46 """Cache entry for modules loaded by getmod()
48 Instances of this class are returned by the getmod()
49 function. They contain three data attributes:
50 * mod - The loaded module
51 * lock - A threading.Lock object, which can be used for
52 manipulating this instance in a thread-safe manner
53 * mtime - The time the file was last modified
55 Additional data attributes can be arbitrarily added for recording
56 any meta-data about the module.
58 def __init__(self, mod = None, mtime = -1):
59 self.lock = threading.Lock()
65 cachelock = threading.Lock()
77 """Load the given file as a module, caching it appropriately
79 The given file is loaded and compiled into a Python module. The
80 compiled module is cached and returned upon subsequent requests
81 for the same file, unless the file has changed (as determined by
82 its mtime), in which case the cached module is discarded and the
83 new file contents are reloaded in its place.
85 The return value is an instance of the cachedmod class, which can
86 be used for locking purposes and for storing arbitrary meta-data
87 about the module. See its documentation for details.
92 entry = modcache[path]
95 modcache[path] = entry
97 if entry.mod is None or sb.st_mtime > entry.mtime:
98 with open(path, "rb") as f:
100 code = compile(text, path, "exec")
101 mod = types.ModuleType(mangle(path))
103 exec(code, mod.__dict__)
105 entry.mtime = sb.st_mtime
108 def chain(env, startreq):
109 path = env["SCRIPT_FILENAME"]
114 if hasattr(mod, "entry"):
117 if hasattr(mod.mod, "wmain"):
118 entry = mod.mod.wmain()
119 elif hasattr(mod.mod, "application"):
120 entry = mod.mod.application
122 if entry is not None:
123 return entry(env, startreq)
124 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "Invalid WSGI handler.")
126 exts["wsgi3"] = chain
128 def addext(ext, handler):
129 p = handler.rindex('.')
131 hname = handler[p + 1:]
132 mod = importlib.import_module(mname)
133 exts[ext] = getattr(mod, hname)
135 def application(env, startreq):
136 """WSGI handler function
138 Handles WSGI requests as per the module documentation.
140 if not "SCRIPT_FILENAME" in env:
141 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
142 path = env["SCRIPT_FILENAME"]
143 base = os.path.basename(path)
145 if p < 0 or not os.access(path, os.R_OK):
146 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
149 return wsgiutil.simpleerror(env, startreq, 500, "Internal Error", "The server is erroneously configured.")
150 return(exts[ext](env, startreq))
153 """Main function for ashd(7)-compatible WSGI handlers
155 Returns the `application' function. If any arguments are given,
156 they are parsed according to the module documentation.
161 addext(arg[1:p], arg[p + 1:])