python: Changed wmain calling convention.
[ashd.git] / python / ashd-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, threading
4 import ashd.proto
5
6 def usage(out):
7     out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
8
9 modwsgi_compat = False
10 opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
11 for o, a in opts:
12     if o == "-h":
13         usage(sys.stdout)
14         sys.exit(0)
15     elif o == "-p":
16         sys.path.insert(0, a)
17     elif o == "-A":
18         modwsgi_compat = True
19 if len(args) < 1:
20     usage(sys.stderr)
21     sys.exit(1)
22
23 try:
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))
27     sys.exit(1)
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])
31         sys.exit(1)
32     handler = handlermod.wmain(*args[1:])
33 else:
34     if not hasattr(handlermod, "application"):
35         sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
36         sys.exit(1)
37     handler = handlermod.application
38
39 def dowsgi(req):
40     env = {}
41     env["wsgi.version"] = 1, 0
42     for key, val in req.headers:
43         env["HTTP_" + key.upper().replace("-", "_")] = val
44     env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
45     env["GATEWAY_INTERFACE"] = "CGI/1.1"
46     env["SERVER_PROTOCOL"] = req.ver
47     env["REQUEST_METHOD"] = req.method
48     env["REQUEST_URI"] = req.url
49     env["PATH_INFO"] = req.rest
50     name = req.url
51     p = name.find('?')
52     if p >= 0:
53         env["QUERY_STRING"] = name[p + 1:]
54         name = name[:p]
55     else:
56         env["QUERY_STRING"] = ""
57     if name[-len(req.rest):] == req.rest:
58         name = name[:-len(req.rest)]
59     env["SCRIPT_NAME"] = name
60     if "Host" in req: env["SERVER_NAME"] = req["Host"]
61     if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
62     if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
63     if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
64     if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
65     if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
66     if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = req["X-Ash-File"]
67     if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
68     env["wsgi.input"] = req.sk
69     env["wsgi.errors"] = sys.stderr
70     env["wsgi.multithread"] = True
71     env["wsgi.multiprocess"] = False
72     env["wsgi.run_once"] = False
73
74     resp = []
75     respsent = []
76
77     def flushreq():
78         if not respsent:
79             if not resp:
80                 raise Exception, "Trying to write data before starting response."
81             status, headers = resp
82             respsent[:] = [True]
83             req.sk.write("HTTP/1.1 %s\n" % status)
84             for nm, val in headers:
85                 req.sk.write("%s: %s\n" % (nm, val))
86             req.sk.write("\n")
87
88     def write(data):
89         if not data:
90             return
91         flushreq()
92         req.sk.write(data)
93         req.sk.flush()
94
95     def startreq(status, headers, exc_info = None):
96         if resp:
97             if exc_info:                # Interesting, this...
98                 try:
99                     if respsent:
100                         raise exc_info[0], exc_info[1], exc_info[2]
101                 finally:
102                     exc_info = None     # CPython GC bug?
103             else:
104                 raise Exception, "Can only start responding once."
105         resp[:] = status, headers
106         return write
107
108     respiter = handler(env, startreq)
109     try:
110         for data in respiter:
111             write(data)
112         if resp:
113             flushreq()
114     finally:
115         if hasattr(respiter, "close"):
116             respiter.close()
117
118 class reqthread(threading.Thread):
119     def __init__(self, req):
120         super(reqthread, self).__init__(name = "Request handler")
121         self.req = req.dup()
122     
123     def run(self):
124         try:
125             dowsgi(self.req)
126         finally:
127             self.req.close()
128     
129 def handle(req):
130     reqthread(req).start()
131
132 ashd.proto.serveloop(handle)