python: Added a util module and moved serveloop thence.
authorFredrik Tolf <fredrik@dolda2000.com>
Tue, 26 Oct 2010 08:41:53 +0000 (10:41 +0200)
committerFredrik Tolf <fredrik@dolda2000.com>
Tue, 26 Oct 2010 08:41:53 +0000 (10:41 +0200)
python/ashd-wsgi
python/ashd/proto.py
python/ashd/util.py [new file with mode: 0644]

index 422fc9f..ae08137 100755 (executable)
@@ -1,7 +1,7 @@
 #!/usr/bin/python
 
 import sys, os, getopt, threading
-import ashd.proto
+import ashd.proto, ashd.util
 
 def usage(out):
     out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
@@ -135,4 +135,4 @@ class reqthread(threading.Thread):
 def handle(req):
     reqthread(req).start()
 
-ashd.proto.serveloop(handle)
+ashd.util.serveloop(handle)
index 12c44bd..90ba012 100644 (file)
@@ -82,13 +82,3 @@ def sendreq(sock, req):
         data += val + '\0'
     data += '\0'
     htlib.sendfd(sock, req.sk.fileno(), data)
-
-def serveloop(handler, sock = 0):
-    while True:
-        req = recvreq(sock)
-        if req is None:
-            break
-        try:
-            handler(req)
-        finally:
-            req.close()
diff --git a/python/ashd/util.py b/python/ashd/util.py
new file mode 100644 (file)
index 0000000..15d61b0
--- /dev/null
@@ -0,0 +1,49 @@
+import os, socket
+import proto
+
+def stdfork(argv, chinit = None):
+    csk, psk = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
+    pid = os.fork()
+    if pid == 0:
+        try:
+            os.dup2(csk.fileno(), 0)
+            for fd in xrange(3, 1024):
+                try:
+                    os.close(fd)
+                except:
+                    pass
+            if chinit is not None:
+                chinit()
+            os.execvp(argv[0], argv)
+        finally:
+            os._exit(127)
+    csk.close()
+    fd = os.dup(psk.fileno())
+    psk.close()
+    return fd
+
+def respond(req, body, status = ("200 OK"), ctype = "text/html"):
+    if type(body) == unicode:
+        body = body.decode("utf-8")
+        if ctype[:5] == "text/" and ctype.find(';') < 0:
+            ctype = ctype + "; charset=utf-8"
+    else:
+        body = str(body)
+    try:
+        req.sk.write("HTTP/1.1 %s\n" % status)
+        req.sk.write("Content-Type: %s\n" % ctype)
+        req.sk.write("Content-Length: %i\n" % len(body))
+        req.sk.write("\n")
+        req.sk.write(body)
+    finally:
+        req.close()
+
+def serveloop(handler, sock = 0):
+    while True:
+        req = proto.recvreq(sock)
+        if req is None:
+            break
+        try:
+            handler(req)
+        finally:
+            req.close()