python: Removed debug message in proto.py.
[ashd.git] / python / ashd-wsgi
CommitLineData
c270f222
FT
1#!/usr/bin/python
2
3import sys, os, getopt, threading
4import ashd.proto
5
6def usage(out):
7 out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
8
9modwsgi_compat = False
10opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
11for 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
19if len(args) < 1:
20 usage(sys.stderr)
21 sys.exit(1)
22
23try:
24 handlermod = __import__(args[0], fromlist = ["dummy"])
25except ImportError, exc:
26 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
27 sys.exit(1)
28if 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:])
33else:
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
39def 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 name = name[:p]
54 env["QUERY_STRING"] = name[p + 1:]
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 write(data):
78 if not data:
79 return
80 if not respsent:
81 if not resp:
82 raise Exception, "Trying to write data before starting response."
83 status, headers = resp
84 respsent[:] = [True]
85 req.sk.write("HTTP/1.1 %s\n" % status)
86 for nm, val in headers:
87 req.sk.write("%s: %s\n" % (nm, val))
88 req.sk.write("\n")
89 req.sk.write(data)
90 req.sk.flush()
91
92 def startreq(status, headers, exc_info = None):
93 if resp:
94 if exc_info: # Interesting, this...
95 try:
96 if respsent:
97 raise exc_info[0], exc_info[1], exc_info[2]
98 finally:
99 exc_info = None # CPython GC bug?
100 else:
101 raise Exception, "Can only start responding once."
102 resp[:] = status, headers
103 return write
104
105 respiter = handler(env, startreq)
106 try:
107 for data in respiter:
108 write(data)
109 write("")
110 finally:
111 if hasattr(respiter, "close"):
112 respiter.close()
113
114class reqthread(threading.Thread):
115 def __init__(self, req):
116 super(reqthread, self).__init__(name = "Request handler")
117 self.req = req.dup()
118
119 def run(self):
120 try:
121 dowsgi(self.req)
122 finally:
123 self.req.close()
124
125def handle(req):
126 reqthread(req).start()
127
128ashd.proto.serveloop(handle)