From: Fredrik Tolf Date: Tue, 26 Oct 2010 08:41:53 +0000 (+0200) Subject: python: Added a util module and moved serveloop thence. X-Git-Tag: 0.4~8 X-Git-Url: http://www.dolda2000.com/gitweb/?p=ashd.git;a=commitdiff_plain;h=4e7888f79c780b6d79420374f5ab3843d7784fad python: Added a util module and moved serveloop thence. --- diff --git a/python/ashd-wsgi b/python/ashd-wsgi index 422fc9f..ae08137 100755 --- a/python/ashd-wsgi +++ b/python/ashd-wsgi @@ -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) diff --git a/python/ashd/proto.py b/python/ashd/proto.py index 12c44bd..90ba012 100644 --- a/python/ashd/proto.py +++ b/python/ashd/proto.py @@ -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 index 0000000..15d61b0 --- /dev/null +++ b/python/ashd/util.py @@ -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()