3 import sys, os, getopt, logging, platform
5 import ashd.scgi, ashd.serve
12 out.write("usage: scgi-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
16 modwsgi_compat = False
18 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:T:m:")
28 sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
29 sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
32 bindhost = "localhost"
36 bindport = int(a[p + 1:])
37 sk.bind((bindhost, bindport))
45 hspec = ashd.serve.parsehspec(a)
50 logging.basicConfig(format="scgi-wsgi(%(name)s): %(levelname)s: %(message)s")
53 # This is suboptimal, since the socket on stdin is not necessarily
54 # AF_UNIX, but Python does not seem to offer any way around it,
56 sk = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
59 handlermod = __import__(args[0], fromlist = ["dummy"])
60 except ImportError, exc:
61 sys.stderr.write("scgi-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
63 if not modwsgi_compat:
64 if not hasattr(handlermod, "wmain"):
65 sys.stderr.write("scgi-wsgi: handler %s has no `wmain' function\n" % args[0])
67 handler = handlermod.wmain(*args[1:])
69 if not hasattr(handlermod, "application"):
70 sys.stderr.write("scgi-wsgi: handler %s has no `application' object\n" % args[0])
72 handler = handlermod.application
76 env["wsgi.version"] = 1, 0
77 if "HTTP_X_ASH_PROTOCOL" in env:
78 env["wsgi.url_scheme"] = env["HTTP_X_ASH_PROTOCOL"]
80 env["wsgi.url_scheme"] = "https"
82 env["wsgi.url_scheme"] = "http"
83 env["wsgi.input"] = sk
84 env["wsgi.errors"] = sys.stderr
85 env["wsgi.multithread"] = True
86 env["wsgi.multiprocess"] = False
87 env["wsgi.run_once"] = False
90 class request(ashd.serve.wsgirequest):
91 def __init__(self, sk, **kw):
92 super(request, self).__init__(**kw)
94 self.sk = self.bsk.makefile("r+")
97 return mkenv(ashd.scgi.readhead(self.sk), self.sk)
99 def handlewsgi(self, env, startreq):
100 return handler(env, startreq)
105 if request._onjython is None:
106 request._onjython = ("java" in platform.system().lower())
107 return request._onjython
110 if request.onjython():
111 self.bsk.setblocking(False)
112 return self.bsk.fileno()
114 def writehead(self, status, headers):
115 w = self.buffer.extend
116 w("Status: %s\n" % status)
117 for nm, val in headers:
118 w("%s: %s\n" % (nm, val))
123 if not request.onjython():
124 ret = self.bsk.send(self.buffer, socket.MSG_DONTWAIT)
126 ret = self.bsk.send(str(self.buffer))
127 self.buffer[:ret] = ""
129 raise ashd.serve.closed()
135 if hspec[0] not in ashd.serve.names:
136 sys.stderr.write("scgi-wsgi: no such request handler: %s\n" % hspec[0])
138 hclass = ashd.serve.names[hspec[0]]
140 hargs = hclass.parseargs(**hspec[1])
141 except ValueError as exc:
142 sys.stderr.write("scgi-wsgi: %s\n" % exc)
145 reqhandler = hclass(**hargs)
148 nsk, addr = sk.accept()
150 reqhandler.handle(request(sk=nsk, handler=reqhandler))