3 import sys, os, getopt, threading
4 import ashd.proto, ashd.util
7 out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
10 opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
24 handlermod = __import__(args[0], fromlist = ["dummy"])
25 except ImportError, exc:
26 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
28 if not modwsgi_compat:
29 if not hasattr(handlermod, "wmain"):
30 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
32 handler = handlermod.wmain(*args[1:])
34 if not hasattr(handlermod, "application"):
35 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
37 handler = handlermod.application
42 return os.path.join(cwd, path)
47 env["wsgi.version"] = 1, 0
48 for key, val in req.headers:
49 env["HTTP_" + key.upper().replace("-", "_")] = val
50 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
51 env["GATEWAY_INTERFACE"] = "CGI/1.1"
52 env["SERVER_PROTOCOL"] = req.ver
53 env["REQUEST_METHOD"] = req.method
54 env["REQUEST_URI"] = req.url
55 env["PATH_INFO"] = req.rest
59 env["QUERY_STRING"] = name[p + 1:]
62 env["QUERY_STRING"] = ""
63 if name[-len(req.rest):] == req.rest:
64 name = name[:-len(req.rest)]
65 env["SCRIPT_NAME"] = name
66 if "Host" in req: env["SERVER_NAME"] = req["Host"]
67 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
68 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
69 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
70 if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
71 if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
72 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
73 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
74 env["wsgi.input"] = req.sk
75 env["wsgi.errors"] = sys.stderr
76 env["wsgi.multithread"] = True
77 env["wsgi.multiprocess"] = False
78 env["wsgi.run_once"] = False
86 raise Exception, "Trying to write data before starting response."
87 status, headers = resp
89 req.sk.write("HTTP/1.1 %s\n" % status)
90 for nm, val in headers:
91 req.sk.write("%s: %s\n" % (nm, val))
101 def startreq(status, headers, exc_info = None):
103 if exc_info: # Interesting, this...
106 raise exc_info[0], exc_info[1], exc_info[2]
108 exc_info = None # CPython GC bug?
110 raise Exception, "Can only start responding once."
111 resp[:] = status, headers
114 respiter = handler(env, startreq)
116 for data in respiter:
121 if hasattr(respiter, "close"):
124 class reqthread(threading.Thread):
125 def __init__(self, req):
126 super(reqthread, self).__init__(name = "Request handler")
136 reqthread(req).start()
138 ashd.util.serveloop(handle)