Added a SCGI-WSGI gateway for Python.
[ashd.git] / python / scgi-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt
4 import socket
5 import ashd.scgi
6
7 def usage(out):
8     out.write("usage: scgi-wsgi [-hA] [-p MODPATH] [-T [HOST:]PORT] HANDLER-MODULE [ARGS...]\n")
9
10 sk = None
11 modwsgi_compat = False
12 opts, args = getopt.getopt(sys.argv[1:], "+hAp:T:")
13 for o, a in opts:
14     if o == "-h":
15         usage(sys.stdout)
16         sys.exit(0)
17     elif o == "-p":
18         sys.path.append(0, a)
19     elif o == "-T":
20         sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21         p = a.rfind(":")
22         if p < 0:
23             bindhost = "hostname"
24             bindport = int(a)
25         else:
26             bindhost = a[:p]
27             bindport = int(a[p + 1:])
28         sk.bind((bindhost, bindport))
29         sk.listen(32)
30     elif o == "-A":
31         modwsgi_compat = True
32 if len(args) < 1:
33     usage(sys.stderr)
34     sys.exit(1)
35
36 if sk is None:
37     # This is suboptimal, since the socket on stdin is not necessarily
38     # AF_UNIX, but Python does not seem to offer any way around it,
39     # that I can find.
40     sk = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
41
42 try:
43     handlermod = __import__(args[0], fromlist = ["dummy"])
44 except ImportError, exc:
45     sys.stderr.write("scgi-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
46     sys.exit(1)
47 if not modwsgi_compat:
48     if not hasattr(handlermod, "wmain"):
49         sys.stderr.write("scgi-wsgi: handler %s has no `wmain' function\n" % args[0])
50         sys.exit(1)
51     handler = handlermod.wmain(args[1:])
52 else:
53     if not hasattr(handlermod, "application"):
54         sys.stderr.write("scgi-wsgi: handler %s has no `application' object\n" % args[0])
55         sys.exit(1)
56     handler = handlermod.application
57
58 ashd.scgi.servescgi(sk, ashd.scgi.wrapwsgi(handler))