PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/isapi_wsgi.py

http://isapi-wsgi.googlecode.com/
Python | 563 lines | 466 code | 34 blank | 63 comment | 13 complexity | 2800ff6d82ba404849c18f8fab079c8a MD5 | raw file
Possible License(s): MIT
  1. """
  2. $Id: isapi_wsgi.py 141 2010-04-12 08:59:21Z mark.john.rees $
  3. This is a ISAPI extension for a wsgi with 2 handlers classes.
  4. - ISAPISimpleHandler which creates a new IsapiWsgiHandler object for
  5. each request.
  6. - ISAPIThreadPoolHandler where the wsgi requests are run on worker threads
  7. from the thread pool.
  8. Dependecies:
  9. - python 2.2+
  10. - win32 extensions
  11. - wsgiref library from http://cvs.eby-sarna.com/wsgiref/
  12. Based on isapi/test/extension_simple.py, PEP 333 etc
  13. """
  14. __author__ = "Mark Rees <mark.john.rees@gmail.com>"
  15. __release__ = "0.4"
  16. __version__ = "$Rev: 141 $ $LastChangedDate: 2010-04-12 10:59:21 +0200 (Mon, 12 Apr 2010) $"
  17. __url__ = "http://isapi-wsgi.googlecode.com"
  18. __description__ = "ISAPI WSGI Handler"
  19. __license__ = "MIT"
  20. #this is first so that we can see import errors
  21. import sys
  22. if hasattr(sys, "isapidllhandle"):
  23. import win32traceutil
  24. try:
  25. import isapi
  26. except ImportError:
  27. raise ImportError("Could not find module isapi. isapi_wsgi requires pywin32")
  28. from isapi import isapicon, ExtensionError
  29. from isapi.simple import SimpleExtension
  30. from isapi.threaded_extension import ThreadPoolExtension
  31. from wsgiref.handlers import BaseHandler
  32. from wsgiref.util import shift_path_info
  33. import sys
  34. import os
  35. import stat
  36. import string
  37. import re
  38. try: from cStringIO import StringIO
  39. except ImportError: from StringIO import StringIO
  40. traceon = 0
  41. def trace(*msgs):
  42. """Write trace message(s) so win32traceutil can display them"""
  43. if not traceon: return
  44. for msg in msgs:
  45. print(msg)
  46. class FoldedCaseString(str):
  47. """
  48. From jaraco.util.string.FoldedCase:
  49. A case insensitive string class; behaves just like str
  50. except compares equal when the only variation is case.
  51. >>> s = FoldedCaseString('hello world')
  52. >>> s == 'Hello World'
  53. True
  54. >>> 'Hello World' == s
  55. True
  56. >>> s.index('O')
  57. 4
  58. >>> s.split('O')
  59. ['hell', ' w', 'rld']
  60. >>> sorted(map(FoldedCaseString, ['GAMMA', 'alpha', 'Beta']))
  61. ['alpha', 'Beta', 'GAMMA']
  62. """
  63. def __lt__(self, other):
  64. return self.lower() < other.lower()
  65. def __gt__(self, other):
  66. return self.lower() > other.lower()
  67. def __eq__(self, other):
  68. return self.lower() == other.lower()
  69. def __hash__(self):
  70. return hash(self.lower())
  71. # cache lower since it's likely to be called frequently.
  72. def lower(self):
  73. self._lower = super(FoldedCaseString, self).lower()
  74. self.lower = lambda: self._lower
  75. return self._lower
  76. def index(self, sub):
  77. return self.lower().index(sub.lower())
  78. def split(self, splitter=' ', maxsplit=0):
  79. pattern = re.compile(re.escape(splitter), re.I)
  80. return pattern.split(self, maxsplit)
  81. class ECBDictAdapter(object):
  82. """
  83. Adapt ECB to a read-only dictionary interface
  84. >>> from fakeecb import FakeECB
  85. >>> ecb = FakeECB()
  86. >>> ecb_dict = ECBDictAdapter(ecb)
  87. >>> ecb_dict['SCRIPT_NAME']
  88. '/'
  89. >>> ecb_dict['PATH_INFO']
  90. '/'
  91. """
  92. def __init__(self, ecb):
  93. self.ecb = ecb
  94. if sys.version_info > (3,0):
  95. if ecb.Version >= 0x00060000:
  96. # we can handle UNICODE_* variables.
  97. self._get_variable = self._get_variable_py3k
  98. else:
  99. self._get_variable = self._get_variable_py3k_iis5
  100. else:
  101. self._get_variable = self._get_variable_py2k
  102. def __getitem__(self, key):
  103. try:
  104. return self._get_variable(key)
  105. except ExtensionError:
  106. raise KeyError, key
  107. # a few helpers specific to the IIS and python version.
  108. def _get_variable(self, key):
  109. raise RuntimeError("not reached: replaced at runtime in the ctor")
  110. def _get_variable_py3k_iis5(self, key):
  111. # IIS5 doesn't support UNICODE_* variable names...
  112. return self.ecb.GetServerVariable(key).decode('latin-1')
  113. def _get_variable_py3k(self, key):
  114. # IIS6 and later on py3k - ask IIS for the unicode version.
  115. return self.ecb.GetServerVariable('UNICODE_' + key)
  116. def _get_variable_py2k(self, key):
  117. # py2k - just use normal string objects.
  118. return self.ecb.GetServerVariable(key)
  119. def path_references_application(path, apps):
  120. """
  121. Return true if the first element in the path matches any string
  122. in the apps list.
  123. >>> path_references_application('/foo/bar', ['foo','baz'])
  124. True
  125. """
  126. # assume separator is /
  127. nodes = filter(None, path.split('/'))
  128. return nodes and nodes[0] in apps
  129. def interpretPathInfo(ecb_server_vars, app_names=[]):
  130. """
  131. Based on the a dictionary of ECB server variables and list of valid
  132. subapplication names, determine the correct PATH_INFO, SCRIPT_NAME,
  133. and IIS_EXTENSION_PATH.
  134. By valid, I mean SCRIPT_NAME + PATH_INFO is always the request path and
  135. SCRIPT_NAME is the path to the WSGi application and PATH_INFO is the path
  136. that the WSGI application expects to handle.
  137. In IIS, the path to the extension sometimes varies from the script name,
  138. particularly when the script map extenison is not '*'. IIS_EXTENSION_PATH
  139. is set to the path that leads to the extension.
  140. Return these values as a dict.
  141. For the following doctests, I use a convention:
  142. vappname : the IIS application
  143. appname : the wsgi application (may be )
  144. subappX : a wsgi sub application (must always follow appname)
  145. proc : a method within the WSGI app (something that should appear in PATH_INFO)
  146. --------------------------
  147. First some common examples
  148. Following is an example case where the extension is installed at the root
  149. of the site, the requested
  150. URL is /proc
  151. >>> ecb_vars = dict(SCRIPT_NAME='/proc', PATH_INFO='/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT')
  152. >>> interpretPathInfo(ecb_vars) == dict(SCRIPT_NAME='', PATH_INFO='/proc', IIS_EXTENSION_PATH='')
  153. True
  154. An example where the extension is installed to a virtual directory below
  155. the root.
  156. URL is /vappname/proc
  157. >>> ecb_vars = dict(SCRIPT_NAME='/vappname/proc', PATH_INFO='/vappname/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT/vappname')
  158. >>> interpretPathInfo(ecb_vars) == dict(SCRIPT_NAME='/vappname', PATH_INFO='/proc', IIS_EXTENSION_PATH='/vappname')
  159. True
  160. An example where the extension is installed to a virtual directory below
  161. the root, and some subapps are present
  162. >>> subapps = ('subapp1', 'subapp2')
  163. URL is /vappname/proc
  164. >>> ecb_vars = dict(SCRIPT_NAME='/vappname/proc', PATH_INFO='/vappname/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT/vappname')
  165. >>> interpretPathInfo(ecb_vars, subapps) == dict(SCRIPT_NAME='/vappname', PATH_INFO='/proc', IIS_EXTENSION_PATH='/vappname')
  166. True
  167. URL is /vappname/subapp1/proc
  168. >>> ecb_vars = dict(SCRIPT_NAME='/vappname/subapp1/proc', PATH_INFO='/vappname/subapp1/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT/vappname')
  169. >>> interpretPathInfo(ecb_vars, subapps) == dict(SCRIPT_NAME='/vappname/subapp1', PATH_INFO='/proc', IIS_EXTENSION_PATH='/vappname', WSGI_SUBAPP='subapp1')
  170. True
  171. ------------------------------
  172. Now some less common scenarios
  173. An example where the extension is installed only to the .wsgi extension to
  174. a virtual directory below the root.
  175. URL is /vappname/any.wsgi/proc
  176. >>> ecb_vars = dict(SCRIPT_NAME='/vappname/any.wsgi', PATH_INFO='/vappname/any.wsgi/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT/vappname')
  177. >>> interpretPathInfo(ecb_vars) == dict(SCRIPT_NAME='/vappname/any.wsgi', PATH_INFO='/proc', IIS_EXTENSION_PATH='/vappname')
  178. True
  179. An example where the extension is installed only to the .wsgi extension at
  180. the root.
  181. URL is /any_path/any.wsgi/proc
  182. >>> ecb_vars = dict(SCRIPT_NAME='/any_path/any.wsgi', PATH_INFO='/any_path/any.wsgi/proc', APPL_MD_PATH='/LM/W3SVC/1/ROOT')
  183. >>> interpretPathInfo(ecb_vars) == dict(SCRIPT_NAME='/any_path/any.wsgi', PATH_INFO='/proc', IIS_EXTENSION_PATH='')
  184. True
  185. How about an extension installed at the root to the .wsgi extension with
  186. subapps
  187. URL is /any_path/any.wsgi/subapp1/proc/foo
  188. >>> ecb_vars = dict(SCRIPT_NAME='/any_path/any.wsgi', PATH_INFO='/any_path/any.wsgi/subapp1/proc/foo', APPL_MD_PATH='/LM/W3SVC/1/ROOT')
  189. >>> interpretPathInfo(ecb_vars, subapps) == dict(SCRIPT_NAME='/any_path/any.wsgi/subapp1', PATH_INFO='/proc/foo', IIS_EXTENSION_PATH='', WSGI_SUBAPP='subapp1')
  190. True
  191. How about an extension installed at the root to the .wsgi extension with
  192. subapps... this time default to the root app.
  193. URL is /any_path/any.wsgi/proc/foo
  194. >>> ecb_vars = dict(SCRIPT_NAME='/any_path/any.wsgi', PATH_INFO='/any_path/any.wsgi/proc/foo', APPL_MD_PATH='/LM/W3SVC/1/ROOT')
  195. >>> interpretPathInfo(ecb_vars, subapps) == dict(SCRIPT_NAME='/any_path/any.wsgi', PATH_INFO='/proc/foo', IIS_EXTENSION_PATH='')
  196. True
  197. """
  198. PATH_INFO = ecb_server_vars['PATH_INFO']
  199. SCRIPT_NAME = ecb_server_vars['SCRIPT_NAME']
  200. IIS_EXTENSION_PATH = getISAPIExtensionPath(ecb_server_vars)
  201. if SCRIPT_NAME == PATH_INFO:
  202. # since they're the same, we're in a * mapped extension; use
  203. # the application path
  204. SCRIPT_NAME = IIS_EXTENSION_PATH
  205. # remove the script name from the path info
  206. if SCRIPT_NAME and PATH_INFO.startswith(SCRIPT_NAME):
  207. _, PATH_INFO = PATH_INFO.split(SCRIPT_NAME, 1)
  208. result = dict(
  209. SCRIPT_NAME=SCRIPT_NAME,
  210. PATH_INFO=PATH_INFO,
  211. IIS_EXTENSION_PATH=IIS_EXTENSION_PATH,
  212. )
  213. # finally, adjust the result if the path info begins with a subapp
  214. if path_references_application(PATH_INFO, app_names):
  215. result.update(WSGI_SUBAPP = shift_path_info(result))
  216. return result
  217. def getISAPIExtensionPath(ecb_server_vars):
  218. """Returns the path to our extension DLL.
  219. This will be blank ('') if installed at the root, or something like
  220. '/foo' or '/bar/foo' if 'foo' is the name of the virtual directory
  221. where this extension is installed.
  222. >>> getISAPIExtensionPath(dict(APPL_MD_PATH='/LM/W3SVC/1/ROOT/test'))
  223. '/test'
  224. >>> getISAPIExtensionPath(dict(APPL_MD_PATH='/LM/W3SVC/1/ROOT'))
  225. ''
  226. This test exercises the less common mixed-case metadata path
  227. >>> getISAPIExtensionPath(dict(APPL_MD_PATH='/LM/W3SVC/1/Root'))
  228. ''
  229. """
  230. # Only way I see how to do this is to fetch the location of our ISAPI
  231. # extension in the metabase then assume that '/ROOT/' is the root!
  232. # It will be something like MD='/LM/W3SVC/1/ROOT/test'
  233. appl_md_path = ecb_server_vars["APPL_MD_PATH"]
  234. appl_md_path = FoldedCaseString(appl_md_path)
  235. site, pos = appl_md_path.split("/ROOT", 1)
  236. return pos
  237. class ISAPIInputWrapper:
  238. # Based on ModPythonInputWrapper in mp_wsgi_handler.py
  239. def __init__(self, ecb):
  240. self._in = StringIO()
  241. self._ecb = ecb
  242. if self._ecb.AvailableBytes > 0:
  243. data = self._ecb.AvailableData
  244. # Check if more data from client than what is in ecb.AvailableData
  245. excess = self._ecb.TotalBytes - self._ecb.AvailableBytes
  246. if excess > 0:
  247. extra = self._ecb.ReadClient(excess)
  248. data = data + extra
  249. self._in.write(data)
  250. # rewind to start
  251. self._in.seek(0)
  252. def next(self):
  253. return self._in.next()
  254. def read(self, size=-1):
  255. return self._in.read(size)
  256. def readline(self, size=-1):
  257. return self._in.readline(size)
  258. def readlines(self, hint=-1):
  259. return self._in.readlines()
  260. def reset(self):
  261. self._in.reset()
  262. def seek(self, *args, **kwargs):
  263. self._in.seek(*args, **kwargs)
  264. def tell(self):
  265. return self._in.tell()
  266. def __iter__(self):
  267. return iter(self._in.readlines())
  268. class ISAPIOutputWrapper:
  269. def __init__(self, ecb):
  270. self.ecb = ecb
  271. def write(self, msg):
  272. self.ecb.WriteClient(msg)
  273. def flush(self):
  274. pass
  275. class ISAPIErrorWrapper:
  276. def write(self, msg):
  277. trace(msg)
  278. def flush(self):
  279. pass
  280. class IsapiWsgiHandler(BaseHandler):
  281. def __init__(self, ecb, path_info):
  282. self.ecb = ecb
  283. self.path_info = path_info
  284. self.stdin = ISAPIInputWrapper(self.ecb)
  285. self.stdout = ISAPIOutputWrapper(self.ecb)
  286. self.stderr = sys.stderr #this will go to the win32traceutil
  287. self.headers = None
  288. self.headers_sent = False
  289. self.wsgi_multithread = False
  290. self.wsgi_multiprocess = False
  291. self.base_env = []
  292. def send_preamble(self):
  293. """Since ISAPI sends preamble itself, do nothing"""
  294. trace("send_preamble")
  295. def send_headers(self):
  296. """Transmit headers to the client, via self._write()"""
  297. trace("send_headers", str(self.headers))
  298. self.cleanup_headers()
  299. self.headers_sent = True
  300. if not self.origin_server or self.client_is_modern():
  301. trace("SendResponseHeaders")
  302. self.ecb.SendResponseHeaders(self.status, str(self.headers), False)
  303. def _write(self, data):
  304. trace("_write", data)
  305. self.ecb.WriteClient(data)
  306. def _flush(self):
  307. trace("_flush")
  308. def get_stdin(self):
  309. trace("get_stdin")
  310. return self.stdin
  311. def get_stderr(self):
  312. trace("get_stderr")
  313. return self.stderr
  314. def add_cgi_vars(self):
  315. trace("add_cgi_vars")
  316. # get standard windows os environment
  317. environ = dict(os.environ.items())
  318. # set standard CGI variables
  319. required_cgienv_vars = ['REQUEST_METHOD', 'SCRIPT_NAME',
  320. 'PATH_INFO', 'QUERY_STRING',
  321. 'CONTENT_TYPE', 'CONTENT_LENGTH',
  322. 'SERVER_NAME', 'SERVER_PORT',
  323. 'SERVER_PROTOCOL', 'REMOTE_ADDR'
  324. ]
  325. ecb_dict = ECBDictAdapter(self.ecb)
  326. for cgivar in required_cgienv_vars:
  327. try:
  328. environ[cgivar] = ecb_dict[cgivar]
  329. except KeyError:
  330. raise AssertionError("missing CGI environment variable %s" % cgivar)
  331. environ.update(self.path_info)
  332. http_cgienv_vars = ecb_dict['ALL_HTTP'].split("\n")
  333. for cgivar in http_cgienv_vars:
  334. pair = cgivar.split(":",1)
  335. try:
  336. environ[pair[0]] = pair[1]
  337. except:
  338. # Handle last list which is not a pair
  339. pass
  340. # Other useful CGI variables
  341. optional_cgienv_vars = ['REMOTE_USER', 'HTTPS',]
  342. for cgivar in optional_cgienv_vars:
  343. try:
  344. environ[cgivar] = ecb_dict[cgivar]
  345. except KeyError:
  346. pass
  347. # and some custom ones.
  348. environ['isapi.ecb'] = self.ecb
  349. self.environ.update(environ)
  350. def _run_app(rootapp, apps, ecb):
  351. ecb_dict = ECBDictAdapter(ecb)
  352. path_info = interpretPathInfo(ecb_dict, apps.keys())
  353. loc = path_info.get('WSGI_SUBAPP')
  354. application = apps.get(loc, rootapp)
  355. # we have to pass path_info because otherwise the handler can't determine
  356. # what the correct path is (because it doesn't know whether it's a
  357. # subapp or not)
  358. handler = IsapiWsgiHandler(ecb, path_info)
  359. trace("Handler")
  360. try:
  361. if application is not None:
  362. handler.run(application)
  363. else:
  364. handler.run(isapi_error)
  365. except ExtensionError:
  366. # error normally happens when client disconnects before
  367. # extension i/o completed
  368. pass
  369. except:
  370. # ToDo:Other exceptions should generate a nice page
  371. trace("Caught App Exception")
  372. pass
  373. # The ISAPI extension - handles requests in our virtual dir, and sends the
  374. # response to the client.
  375. class ISAPISimpleHandler(SimpleExtension):
  376. '''Python Simple WSGI ISAPI Extension'''
  377. def __init__(self, rootapp=None, **apps):
  378. trace("ISAPISimpleHandler.__init__")
  379. self.rootapp = rootapp
  380. self.apps = apps
  381. SimpleExtension.__init__(self)
  382. def HttpExtensionProc(self, ecb):
  383. trace("Enter HttpExtensionProc")
  384. _run_app(self.rootapp, self.apps, ecb)
  385. ecb.close()
  386. trace("Exit HttpExtensionProc")
  387. return isapicon.HSE_STATUS_SUCCESS
  388. def TerminateExtension(self, status):
  389. trace("TerminateExtension")
  390. class ISAPIThreadPoolHandler(ThreadPoolExtension):
  391. '''Python Thread Pool WSGI ISAPI Extension'''
  392. def __init__(self, rootapp=None, **apps):
  393. trace("ISAPIThreadPoolHandler.__init__")
  394. self.rootapp = rootapp
  395. self.apps = apps
  396. ThreadPoolExtension.__init__(self)
  397. def Dispatch(self, ecb):
  398. trace("Enter Dispatch")
  399. _run_app(self.rootapp, self.apps, ecb)
  400. ecb.DoneWithSession()
  401. trace("Exit Dispatch")
  402. def isapi_error(environ, start_response):
  403. '''Send a nice error page to the client'''
  404. status = '404 OK'
  405. start_response(status, [('Content-type', 'text/plain')])
  406. return ['Page not found']
  407. #-----------------------------------------------------------------------------
  408. def test(environ, start_response):
  409. '''Simple app as per PEP 333'''
  410. status = '200 OK'
  411. start_response(status, [('Content-type', 'text/plain')])
  412. return ['Hello world from isapi!']
  413. # The entry points for the ISAPI extension.
  414. def __ExtensionFactory__():
  415. return ISAPISimpleHandler(test)
  416. # Our special command line customization.
  417. # Pre-install hook for our virtual directory.
  418. def PreInstallDirectory(params, options):
  419. # If the user used our special '--description' option,
  420. # then we override our default.
  421. if options.description:
  422. params.Description = options.description
  423. # Post install hook for our entire script
  424. def PostInstall(params, options):
  425. print "Extension installed"
  426. # Handler for our custom 'status' argument.
  427. def status_handler(options, log, arg):
  428. "Query the status of something"
  429. print "Everything seems to be fine!"
  430. custom_arg_handlers = {"status": status_handler}
  431. if __name__=='__main__':
  432. # If run from the command-line, install ourselves.
  433. from isapi.install import *
  434. params = ISAPIParameters(PostInstall = PostInstall)
  435. # Setup the virtual directories - this is a list of directories our
  436. # extension uses - in this case only 1.
  437. # Each extension has a "script map" - this is the mapping of ISAPI
  438. # extensions.
  439. sm = [
  440. ScriptMapParams(Extension="*", Flags=0)
  441. ]
  442. vd = VirtualDirParameters(Name="isapi-wsgi-test",
  443. Description = "ISAPI-WSGI Test",
  444. ScriptMaps = sm,
  445. ScriptMapUpdate = "replace",
  446. # specify the pre-install hook.
  447. PreInstall = PreInstallDirectory
  448. )
  449. params.VirtualDirs = [vd]
  450. # Setup our custom option parser.
  451. from optparse import OptionParser
  452. parser = OptionParser('') # black usage, so isapi sets it.
  453. parser.add_option("", "--description",
  454. action="store",
  455. help="custom description to use for the virtual directory")
  456. HandleCommandLine(params, opt_parser=parser,
  457. custom_arg_handlers = custom_arg_handlers)