summaryrefslogtreecommitdiffstats
path: root/silpa/jsonrpc/cgiwrapper.py
blob: a5bc2b0036c996aa1526092fb9805f0fdc81b156 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import sys, os
from jsonrpc import ServiceHandler

class CGIServiceHandler(ServiceHandler):
    def __init__(self, service):
        if service == None:
            import __main__ as service

        ServiceHandler.__init__(self, service)

    def handleRequest(self, fin=None, fout=None, env=None):
        if fin==None:
            fin = sys.stdin
        if fout==None:
            fout = sys.stdout
        if env == None:
            env = os.environ
        
        try:
            contLen=int(env['CONTENT_LENGTH'])
            data = fin.read(contLen)
        except Exception, e:
            data = ""

        resultData = ServiceHandler.handleRequest(self, data)
        
        response = "Content-Type: text/plain\n"
        response += "Content-Length: %d\n\n" % len(resultData)
        response += resultData
        
        #on windows all \n are converted to \r\n if stdout is a terminal and  is not set to binary mode :(
        #this will then cause an incorrect Content-length.
        #I have only experienced this problem with apache on Win so far.
        if sys.platform == "win32":
            try:
                import  msvcrt
                msvcrt.setmode(fout.fileno(), os.O_BINARY)
            except:
                pass
        #put out the response
        fout.write(response)
        fout.flush()

def handleCGI(service=None, fin=None, fout=None, env=None):
    CGIServiceHandler(service).handleRequest(fin, fout, env)